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

Access class member within callback when inside ES6 class statement

本文关键字:成员 回调 访问 语句 ES6      更新时间:2023-09-26

重要信息我正在使用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.
      }
    );
  }
}

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

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

引用:

  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions