toddmo toddmo - 2 months ago 5
Javascript Question

Access class member within callback when inside ES6 class statement

Important I'm using the ES6 class statement. Answers about "classes" defined with a function don't apply because something like

var this = that
are not allowed in a class statement. The answers I've seen on this don't work. No variables outside the callback are visible.

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

Answer

You can follow either of the two:

  Load() {
    const that = this;

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

or

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

References: