在 promise 的 then 回调中,this 指向取决于调用方式:普通函数默认指向 undefined(严格模式)或全局对象,箭头函数继承定义时的词法作用域。要保留外部 this,使用箭头函数或 bind 绑定;若需明确指向实例,优先用箭头函数。

为什么 then 中的 this 会丢失
因为 then 接收的是普通函数时,Promise 内部通过 [[Call]] 调用它,不传入 this 绑定,导致 this 变为 undefined。例如在类方法中直接传 this.method,this 将不再指向实例。

class MyClass {
constructor() {
this.value = 42;
}
getData() {
return new Promise((resolve) => {
setTimeout(() => resolve(this.value), 100);
});
}
}
const instance = new MyClass();
// 错误用法:this 丢失
instance.getData().then(function callback(val) {
console.log(this); // undefined (strict mode)
});
// 正确用法:箭头函数继承 this
instance.getData().then((val) => {
console.log(this.value); // 42
});
如何确保 this 指向正确
使用箭头函数是最简洁的方式,因为它自动捕获外层 this。也可用 bind 显式绑定,但需注意 bind 返回新函数,不能用于链式调用中的动态 this。对于类方法,推荐在构造函数中绑定或在定义时使用箭头函数属性。
使用 Husky 将 pre-commit、pre-push 和 commit-msg 检查集成到仓库中,以便代理和开发人员在更改离开工作站之前运行相同的本地防护措施。

class MyClass {
constructor() {
this.value = 42;
// 方式一:构造函数中绑定
this.getData = this.getData.bind(this);
}
getData() {
return new Promise((resolve) => {
setTimeout(() => resolve(this.value), 100);
});
}
}
const instance = new MyClass();
instance.getData().then(function callback(val) {
console.log(this.value); // 42
});
// 方式二:使用箭头函数属性(ES6+)
class MyClass2 {
constructor() {
this.value = 42;
}
getData = () => {
return new Promise((resolve) => {
setTimeout(() => resolve(this.value), 100);
});
};
}
const instance2 = new MyClass2();
instance2.getData().then(function callback(val) {
console.log(this.value); // 42
});
当 then 中需要访问实例其他方法时怎么办
如果 then 回调中需要调用实例的其他方法,必须确保 this 正确指向实例。否则调用 this.otherMethod() 会报错。解决方案同上:使用箭头函数或预先绑定 this。避免在 then 中使用普通函数 unless 你显式绑定了 this。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










