Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid losing object this context in Typescript?

I have created a getter field on a class that returns a method, which is invoked with some inputs. Here is the method:

private gainItem(rewardItem: Item) {
  console.log(this);
  //Give item to user
}

Here is the getter field on the class containing this method:

private get npcPlayerInterface(): NpcPlayerInterface {
  return {
    gainItem: this.gainItem,
  };
}

I then pass the getter to another class like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this.npcChatState = new NpcChatState(this.npcPlayerInterface);

Finally, this is how it is invoked inside the npcChatState class:

npcPlayerInterface.gainItem({ id: ItemId.CAR_BLUE, name: 'Blue CAR' });

The console.log(this) statement shows that the this keyword refers to another object, not the one that I want. How can I fix this without using bind() or this-aliasing?

>Solution :

Just use arrow syntax:

private gainItem = (rewardItem: Item) => {
    console.log(this);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading