箭头函数的 this 继承外层普通函数作用域的 this 值,不绑定执行上下文;不能用 call/apply/bind 修改,不可作为构造函数,无 arguments 对象。
箭头函数的 this 不绑定执行上下文,而是继承外层普通函数作用域中的 this 值——这是它最核心的特点,也是和传统函数最根本的区别。
它不会创建自己的执行上下文,所以调用时不会重新绑定 this。无论怎么调用(直接调用、作为方法、用 call/apply/bind),它的 this 都始终等于定义时所在词法作用域的 this。
比如在对象方法或事件回调中使用箭头函数:
const obj = {
name: 'Alice',
regularFunc() {
console.log(this.name); // 'Alice'
setTimeout(function() {
console.log(this.name); // undefined(非严格模式下是 window)
}, 100);
setTimeout(() => {
console.log(this.name); // 'Alice',继承外层 regularFunc 的 this
}, 100);
}
};
再比如 React 类组件中,常把箭头函数写在类属性上,避免手动 bind:
his.state); }` + `
需要动态绑定 this 的场景就不适合:
基本上就这些。记住一句口诀:箭头函数的 this 看定义位置,不看调用方式。