4

从异步方法调用时如何引用类实例。

class Senders {
  callSendAPI() {
    //Some code here
  }
  sendText() {
    this.callSendAPI();
  }
  async sendCards() {
    var dbpromise = await db.call();
    console.log('this= ', this);
    this.callSendAPI();
  }
}
export {Senders};

这=未定义

4

1 回答 1

2

问题在于您正在使用的任何转译器(如果您正在使用一个转译器),或者是给定调用方式的函数的上下文。我在 NodeJS v7.x 中运行了以下代码段,它工作得很好,显示 this 的值是 Senders 的一个类实例。

class Senders {
  async sendCards() {
    console.log('this= ', this);
  }
}

new Senders().sendCards();

如果您确定它不是您的转译器,请尝试在调用函数时使用bindcall / apply来控制执行上下文。

于 2017-02-24T19:54:04.550 回答