构造函数中的范围错误(ES6)

Scope error in constructor (ES6)

我遇到了一个奇怪的错误 当我使用新版本的 ES6 时。当我 运行 这段代码时,我得到 ReferenceError: alertBox is not defined。有什么方法可以在这个函数中调用 alertBox 吗?提前致谢:)

这是代码

class main {
    constructor(data){
    this.data=data;

    // this one works
    this.alertBox(this.data);

    this.watchFile(function(){
      // this one throws error
      this.alertBox(this.data);
    });
    }

  alertBox(data){
    alert(data);
  }

  watchFile(cb){
    cb("changed");
  }
}

// app.js
new main("hello");

您可以在此处找到代码段:https://repl.it/FJUo

通过将普通函数传递给 watchFile,您将失去 this 的上下文。在 ES6 中,您可以使用 "arrow function" 语法来创建一个保持正确上下文的函数。

this.watchFile(() => {
    this.alertBox(this.data);
});