Search code examples
typescriptjavascript-objectsthis

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:

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);
    }