Search code examples
javascriptnode.jsasync-awaitprototype

undefined this in async prototype function


my question is similar to this. But I want to put async keyword to a prototype function, not to a constructor.

"this" is undefined in the prototype function saySomething. Why? How can I use async in class?

var Person =  function() {
  console.log("CALLED PERSON")
};

Person.prototype.saySomething = async () => {
  console.log(this);//undefined
};

(async function(){
  var ape = new Person();
  await ape.saySomething();
}());


Solution

  • You should not use arrow function expressions (because it doesn't have own bindings to the this) but a regular function expression:

    var Person =  function() {
      console.log("CALLED PERSON")
    };
    
    Person.prototype.saySomething = async function() {
      console.log(this);
    };
    
    (async function(){
      var ape = new Person();
      await ape.saySomething();
    }());

    Or another example using class (as suggested by @nickf):

    class Person {
      constructor() {
        console.log("CALLED PERSON")
      }
      
      async saySomething() {
        console.log(this);
      };
    }
    
    (async function(){
      var ape = new Person();
      await ape.saySomething();
    }());