代碼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)
1 回答

BIG陽
TA貢獻1859條經驗 獲得超6個贊
1>. 回調函數為匿名函數時,回調函數的this會指向window,需要對回調函數bind(this)。
2>. 回調函數為箭頭函數時,回調函數的this會指向他的直接上層,本例中指向dog。
添加回答
舉報
0/150
提交
取消