箭头函数的 this 指向哪⾥?
参考答案
结论
箭头函数的 this 不指向调用者,也不指向自身,而是**继承自定义时所在的外层作用域(词法作用域)的 this,且一旦确定无法改变**(call/apply/bind 都改不了)。
const obj = {
name: 'tom',
regular() { console.log(this.name); }, // 调用时决定 → obj
arrow: () => console.log(this.name), // 定义时决定 → 外层(模块/全局)
};
obj.regular(); // 'tom'
obj.arrow(); // undefined(浏览器里是 window.name,通常为空)
机制
- 箭头函数**没有自己的
this**,内部访问this时沿作用域链向上查找(和普通变量一样)。 - 因此它的
this由定义位置决定,与调用方式无关:
function Outer() {
this.v = 1;
this.get = () => this.v; // 这里的 this 是 Outer 实例
}
new Outer().get(); // 1
bind/call/apply对箭头函数无效(因为this不是它自己的绑定):
const f = () => this;
f.call({ a: 1 }); // 仍然是外层 this
- 箭头函数也没有
arguments、super、new.target,需要时用 rest 参数或外层变量。
常见场景
1. 回调中保留 this(最经典用途)
class Timer {
constructor() { this.n = 0; }
start() {
setInterval(() => { this.n++; }, 1000); // ✅ this 是 Timer 实例
// setInterval(function(){ this.n++ }, 1000) // ❌ this 是定时器/全局
}
}
2. 数组方法回调
[1,2].map(x => x * this.factor); // this 沿用外层
3. 对象方法不要用箭头函数
const o = { name: 'a', say: () => this.name }; // ❌ this 不是 o
判断口诀
"箭头函数的 this 看定义位置的外层函数/作用域":
- 定义在普通函数内 → 沿用该函数的
this; - 定义在顶层(模块/全局) →
undefined(模块)或window(脚本); - 定义在 class 字段/方法内 → 沿用实例或方法的
this(类字段箭头函数会绑定实例)。
注意
- 箭头函数不能用作构造器,
new会报错。 - 不能用作
arguments.callee、不能用yield(不能是 Generator)。 - 在对象字面量里不要用箭头函数做方法(拿不到对象自身)。
- Vue/React 中在
methods/class 方法里要慎用,避免this指向错乱。