About the pointing problem of this in Promise?

< H1 > Code < / H1 >
undefined
(node:5784) UnhandledPromiseRejectionWarning: TypeError: Cannot read property "name" of undefined
    at say (D:\NodeJS\Test\test2.js:18:22)

class Dog {
  constructor() {
    this.name = 'adong';
  }

  start() {
    this.p().then(this.say.bind(this));
  }

  p() {
    return new Promise((resolve, reject)=>{
      resolve('good');
    })
  }
  
  say(str) {
    console.log(this);
    console.log(this.name + str);
  }
}

let dog = new Dog();
dog.start();

the essence of your above call writing is:

class Dog {
  constructor() {
    this.name = 'adong';
  }

  start() {
    // this.p().then(this.say)  
    this.p().then(function(str){
        console.log(str);  // good
        console.log(this); //undefined
        //console.log(this.name + str); //this.name
    });
  }

  p() {
    return new Promise((resolve, reject)=>{
      resolve('good');
    })
  }
  
  say(str) {
    console.log(this);
    console.log(this.name + str); 
  }
}

let dog = new Dog();
dog.start();
The then method of

promise passes in a callback function parameter! So then (this.say) essentially only uses this.say as a parameter, so there is no this
1 >. When the callback function is anonymous, the this of the callback function will point to the callback function bind (this) that window, needs.
2 >. When the callback function is an arrow function, the this of the callback function points directly to its upper layer, in this case to dog.


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();
Menu