代码
class Dog {
constructor() {
this.name = 'adong';
}
start() {
this.p().then(this.say);
}
p() {
return new Promise((resolve, reject)=>{
resolve('good');
})
}
say(str) {
console.log(this);
console.log(this.name + str);
}
}
let dog = new Dog();
dog.start();
题目描述
say
方法单独调用时没有问题的,但是在Promise
的then
里面再调用this
就变为undefined
了,哪个大神帮忙分析一下,谢谢!
错误显示
undefined
(node:5784) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of undefined
at say (D:\NodeJS\Test\test2.js:18:22)
你上面的调用写法,其本质就是:
promise的then方法传入的是一个回调函数参数!所以 then(this.say)实质只是将this.say作为一个参数使用,所以不存在this
1>. 回调函数为匿名函数时,回调函数的this会指向window,需要对回调函数bind(this)。
2>. 回调函数为箭头函数时,回调函数的this会指向他的直接上层,本例中指向dog。