谈谈箭头函数
基本概念
箭头函数是ES6新增的函数定义的方式,使用箭头符号=>。在箭头函数中,this的作用域与它周围代码作用域相同,因此也称为 “词法作用域函数” 。
const add = (a,b)=>a+b;
箭头函数与普通函数的不同
- 箭头函数不能new,不能定义构造器。
- 没有自己的
arguments对象。 - this绑定方法失效,例如:call、apply、bind。
this的行为
箭头函数不会创建自己的 this,它的 this 继承自定义它时所在的作用域。
而普通函数的 this 取决于调用方式。
const obj = {
value: 10,
normalFunc: function() {
console.log(this.value); // this 指向 obj
},
arrowFunc: () => {
console.log(this.value); // this 指向外层作用域(不是 obj)
}
};
obj.normalFunc(); // 输出 10
obj.arrowFunc(); // 输出 undefined(或外层作用域的 this)
能够使用的场景
回调函数
const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2);
Promise 链式调用
fetch('/api')
.then(res => res.json())
.then(data => console.log(data));
简单逻辑单行完成
const multiply = (x,y) => x * y;
不能够使用的场景
对象方法中使用
这种方式会让对象丢失this,导致this指向的不是对象本身,而是外层作用域。
const obj = {
name: 'ErMao',
age: 28,
say: () => {
console.log(`My name is ${this.name}, I'm ${this.age} years old`);
}
};
obj.say();
需要arguments的地方
箭头函数不存在arguments对象,使用会报错。
const func1 = () => {
console.log(arguments)
}
func1(1,2,3)
如果需要使用 类似的功能,可以使用以下方法:
const func1 = (...args) => {
console.log(args)
}
func1(1,2,3)
构造函数
不能用作构造函数,无法使用new创建一个新对象。
不能通过call、apply、bind修改this指向
由于this指向指向的是词法作用域中的this值,所以无法修改。