1

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();
}());
falinsky
  • 7,229
  • 3
  • 32
  • 56
Herbert
  • 540
  • 1
  • 6
  • 18

1 Answers1

3

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();
}());
falinsky
  • 7,229
  • 3
  • 32
  • 56