Node.js Promise链中this指向丢失问题求助(新手求指导)
问题原因
当你把this.third作为参数传递给.then()时,传递的只是该方法的函数引用,并未绑定到当前的Trial实例。Promise调用这个函数时,执行上下文的this会变成undefined(严格模式下的默认行为),导致无法访问this.name。
解决方法
方法1:在.then()中用bind绑定this
直接在传递给.then()时,通过bind把方法绑定到当前实例:
async first() { return this.second() .then(this.third.bind(this)) }
方法2:用箭头函数包裹调用
箭头函数会继承外层作用域的this,通过箭头函数调用third方法可以保证上下文正确:
async first() { return this.second() .then(() => this.third()) }
方法3:在构造函数中提前绑定方法
在类的构造函数里,把需要用到的方法提前绑定到实例,后续调用时this始终指向实例:
constructor(name) { this.name = name this.second = this.second.bind(this) this.third = this.third.bind(this) } async first() { return this.second() .then(this.third) }
方法4:使用类字段定义箭头函数方法
直接把类方法定义为箭头函数,方法会自动绑定到实例,无需额外处理:
class Trial { constructor(name) { this.name = name } third = async () => { console.log(`third ${this.name}`, ...arguments) } second = async () => { console.log(`second ${this.name} this is inside 2nd function`) } async first() { return this.second() .then(this.third) } }
内容的提问来源于stack exchange,提问作者Vinayak Shantaram Joshi
相关产品推荐
相关产品推荐

