在ES6类语句中访问回调内的类成员

时间:2016-09-19 00:58:36

标签: javascript es6-class

重要我正在使用ES6类语句。关于使用函数定义的“类”的答案不适用,因为类语句中不允许使用var this = that之类的内容。我在这看到的答案不起作用。回调外没有变量可见。

WebPageReader.Storage = class {
  constructor(object) {
    this.Object = object;
    var self = this; // self is out of scope when constructor completes
  }

  // var self = this; // not allowed here

  Load() {
    chrome.storage.sync.get('somesetting',
      function (setting) {
        console.log(this.Object); // I need to do something with this.Object defined at the class level, but this points to something besides my class.
      }
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您可以按照以下两种方法之一:

  Load() {
    const that = this;

    chrome.storage.sync.get('somesetting',
      function (setting) {
        console.log(that.Object);
      }
    );
  }

  Load() {
    chrome.storage.sync.get('somesetting',
      setting => {
        console.log(this.Object);
      }
    );
  }

参考文献: