关于Promise中this的指向问题?

代码

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方法单独调用时没有问题的,但是在Promisethen里面再调用this就变为undefined了,哪个大神帮忙分析一下,谢谢!

错误显示

undefined
(node:5784) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of undefined
    at say (D:\NodeJS\Test\test2.js:18:22)


holdtom
浏览 2068回答 1
1回答

BIG阳

1>. 回调函数为匿名函数时,回调函数的this会指向window,需要对回调函数bind(this)。2>. 回调函数为箭头函数时,回调函数的this会指向他的直接上层,本例中指向dog。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Vue.js
React.JS