重要我正在使用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.
}
);
}
}
答案 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);
}
);
}
参考文献: