为了账号安全,请及时绑定邮箱和手机立即绑定

关于Promise中this的指向问题?

关于Promise中this的指向问题?

holdtom 2019-01-04 16:28:23
代码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。

查看完整回答
反对 回复 2019-01-04
  • 1 回答
  • 0 关注
  • 2061 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信