0

重要的是,我使用的是 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.
      }
    );
  }
}
4

1 回答 1

1

您可以遵循以下两者中的任何一个:

  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);
      }
    );
  }

参考:

于 2016-09-19T01:08:20.817 回答