箭头函数的 this 指向什么?
参考答案
箭头函数没有自己的 this,它在定义时捕获外层(词法)作用域的 this,之后不会被调用方式改变(call/apply/bind 也改不了)。
const obj = {
name: 'A',
normal() { return this.name; }, // 'A'
arrow: () => this?.name, // 定义处的 this(模块/全局)
};
要点:
- 嵌套箭头函数逐层向上找最近的非箭头函数或全局;
- 类字段箭头方法可固定实例 this(常用于回调);
- 不能 new,也没有 arguments/super/new.target;
- 适合回调、需要保留外层 this 的场景;对象方法、事件处理需要动态 this 时不要用。