如何避免在 Typescript 中丢失对象 this 上下文?

How to avoid losing object this context in Typescript?

我在 class 上创建了一个 getter 字段,returns 一个方法,通过一些输入调用该方法。方法如下:

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

这是包含此方法的 class 上的 getter 字段:

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

然后我将 getter 传递给另一个 class,如下所示:

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

最后,这是在 npcChatState class 中调用它的方式:

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

console.log(this) 语句显示 this 关键字引用了另一个对象,而不是我想要的对象。如何在不使用 bind() 或 this-aliasing 的情况下解决此问题?

只需使用箭头语法:

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