本篇文章主要给大家介绍javascript箭头函数和普通函数的区别,希望对需要的朋友有所帮助!
箭头函数——ES6中引入的一个新特性——支持用JavaScript编写简洁的函数。虽然普通函数和箭头函数的工作方式相似,但是它们之间有一些有趣的区别,如下所述。
语法
普通函数的语法:
let x = function function_name(parameters){
// 函数体
};
|
普通函数的例子:
let square = function(x){
return (x*x);
};
console.log(sqaure(9));
|
输出:

箭头函数的语法:
let x = (parameters) => {
// 函数体
};
|
箭头函数的例子:
var square = (x) => {
return (x*x);
};
console.log(square(9));
|
输出:

使用this关键字
与普通函数不同,箭头函数没有自己的this。
例如:
let user = {
name: "GFG",
gfg1:() => {
console.log("hello " + this.name);
},
gfg2(){
console.log("Welcome to " + this.name);
}
};
user.gfg1();
user.gfg2();
|
输出:

arguments对象的可用性
arguments对象在箭头函数中不可用,但在普通函数中可用。
普通函数的例子:
let user = {
show(){
console.log(arguments);
}
};
user.show(1, 2, 3);
|
输出:

箭头函数的例子:
let user = {
show_ar : () => {
console.log(...arguments);
}
};
user.show_ar(1, 2, 3);
|
输出:

使用new关键字
使用函数声明或表达式创建的普通函数是“可构造的”和“可调用的”。由于普通函数是可构造的,因此可以使用'new'关键字调用它们。但是,箭头函数只是“可调用”而不是可构造的。因此,在尝试使用new关键字构造不可构造的箭头函数时,我们将得到一个运行时错误。
普通函数的例子:
let x = function(){
console.log(arguments);
};
new x =(1,2,3);
|
输出:

箭头函数的例子:
let x = ()=> {
console.log(arguments);
};
new x(1,2,3);
|
输出:

(责任编辑:yang) |