箭头函数是JavaScript的ES6版本中引入的函数之一。与常规函数相比,它可以使您以更简洁的方式创建函数。例如, 该函数
// 函数表达式
let x = function(x, y) {
return x * y;
}
可以写成
// 使用箭头函数
let x = (x, y) => x * y;
使用箭头函数。
箭头函数的语法为:
let myFunction = (arg1, arg2, ...argN) => {
statement(s)
}
这里,
myFunction
是函数的名称 arg1,arg2,... argN
是函数参数statement
是函数体如果主体具有单个语句或表达式,则可以将箭头函数编写为:
let myFunction = (arg1, arg2, ...argN) => expression
如果函数不带任何参数,则应使用空括号。例如,
let greet = () => console.log('Hello');
greet();//Hello
如果一个函数只有一个参数,则可以省略括号。例如,
let greet = x => console.log(x);
greet('Hello');//Hello
您还可以动态创建一个函数并将其用作表达式。例如,
let age = 5;
let welcome = (age < 18) ?
() => console.log('Baby') :
() => console.log('Adult');
welcome();//Baby
如果函数主体具有多个语句,则需要将它们放在大括号 {}
中。例如,
let sum = (a, b) => {
let result = a + b;
return result;
}
let result1 = sum(5,7);
console.log(result1);//12
在常规函数中,this关键字指向调用它的函数。
但是,this
与箭头函数无关。箭头函数没有自己的this
。因此,每当您调用this
时,它都引用其父作用域。例如,
常规函数示例
function Person() {
this.name = 'Jack',
this.age = 25,
this.sayName = function () {
//这是可以访问的
console.log(this.age);
function innerFunc() {
//this 指的是全局对象
console.log(this.age);
console.log(this);
}
innerFunc();
}
}
let x = new Person();
x.sayName();
输出
25 undefined Window {}
内部箭头函数示例
function Person() {
this.name = 'Jack',
this.age = 25,
this.sayName = function () {
console.log(this.age);
let innerFunc = () => {
console.log(this.age);
}
innerFunc();
}
}
const x = new Person();
x.sayName();
输出
25 25
常规函数具有参数绑定。这就是为什么在将参数传递给常规函数时可以使用arguments
关键字访问它们的原因。例如,
let x = function () {
console.log(arguments);
}
x(4,6,7);//Arguments [4, 6, 7]
箭头函数没有参数绑定。当您尝试使用箭头函数访问参数时,它将给出错误。例如,
let x = () => {
console.log(arguments);
}
x(4,6,7);
// ReferenceError: Can't find variable: arguments
要解决此问题,可以使用 Spread 语法。例如,
let x = (...n) => {
console.log(n);
}
x(4,6,7);//[4, 6, 7]
箭头函数提供了更好的语法来编写promise和回调。例如,
// ES5
asyncFunction().then(function() {
return asyncFunction1();
}).then(function() {
return asyncFunction2();
}).then(function() {
finish;
});
可以写成
// ES6
asyncFunction()
.then(() => asyncFunction1())
.then(() => asyncFunction2())
.then(() => finish);
1. 不应使用箭头函数在对象内部创建方法。
let person = {
name: 'Jack',
age: 25,
sayName: () => {
//this refers to the global .....
//
console.log(this.age);
}
}
person.sayName();//undefined
2. 不能将箭头函数用作构造函数。例如,
let Foo = () => {};
let foo = new Foo();//TypeError: Foo is not a constructor
注意: ES6 中引入了箭头函数。某些浏览器可能不支持箭头函数的使用。访问 JavaScript箭头函数支持以了解更多信息。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
但是箭头函数没有自己的this,所以不能作为构造函数使用,也不能通过new操作符调用。