Recently, I implemented a getter field on a class that returns a method and then is invoked with certain inputs. Let me show you the method in question:
private gainItem(rewardItem: Item) {
console.log(this);
//Give item to user
}
Now, let's take a look at the getter field within this class containing the aforementioned method:
private get npcPlayerInterface(): NpcPlayerInterface {
return {
gainItem: this.gainItem,
};
}
Subsequently, I passed this getter to another class as shown below:
this.npcChatState = new NpcChatState(this.npcPlayerInterface);
Finally, here is how it was called inside the npcChatState
class:
npcPlayerInterface.gainItem({ id: ItemId.CAR_BLUE, name: 'Blue CAR' });
The issue arises when the console.log(this)
statement reveals that the this
keyword references a different object than intended. How can I resolve this dilemma without resorting to using bind()
or this-aliasing?