在 ES6 class 语句中访问回调中的 class 成员
Access class member within callback when inside ES6 class statement
重要 我使用的是 ES6 class 语句。关于用函数定义的 "classes" 的答案不适用,因为 class 语句中不允许使用类似 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);
}
);
}
参考文献:
重要 我使用的是 ES6 class 语句。关于用函数定义的 "classes" 的答案不适用,因为 class 语句中不允许使用类似 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);
}
);
}
参考文献: