箭头函数的 this 指向有什么特殊性?
请说明箭头函数中 this 的绑定规则,以及为什么箭头函数不适合作为对象方法。
回答
小字辈
箭头函数 this 规则:
- 不绑定自己的 this,不使用以上四种绑定规则
- this 继承自外层(词法作用域)的普通函数的 this
- 本质是其
[[ThisMode]]为lexical
示例:
const obj = {
name: 'obj',
regular: function() { console.log(this.name); },
arrow: () => console.log(this.name)
};
obj.regular(); // 'obj'(隐式绑定)
obj.arrow(); // undefined(箭头函数的 this 来自外层,此处为全局/模块作用域)
不适合作为对象方法的原因:
- 对象字面量的
{}不创建作用域,箭头函数的 this 指向外层(全局) - 无法被 call/apply/bind 改变
- React 中 class 字段使用箭头函数自动绑定 this 是正确用法(class 构造函数执行时的 this 指向实例)
适合场景:
- 回调函数(setTimeout、事件监听中需要外层 this)
- 数组高阶方法(map/filter/reduce)
- React 函数组件中避免 this 绑定问题