我不确定是否访问 this
ECMAScript 6 类中的上下文。
在这个例子中我想调用方法 addItem(..)
类(class){this.addItem(data.points);}
如何正确绑定(bind)类的 this-Conext?
class TEST {
constructor() {}
testMethod() {
for (let i = 1; i <= 10; i++) {
$.getJSON("test/" + i + ".json", function (data) {
this.addItem(data.points);
});
}
}
}
最佳答案
尝试下面的代码片段。
class TEST {
constructor() {}
testMethod() {
for (let i = 1; i <= 10; i++) {
$.getJSON("test/" + i + ".json", function(data) {
this.addItem(data.points);
}.bind(this)); // bind the this of the function you send to $.getJSON to the this of testMethod
}
}
}
替代方式:
使用箭头函数,因为它们继承了外部 clojure 的词法范围。
class TEST {
constructor() {}
testMethod() {
for (let i = 1; i <= 10; i++) {
$.getJSON("test/" + i + ".json", data => {
this.addItem(data.points); // this is the this of testMethod
});
}
}
}
关于javascript - ECMAScript 6 将此上下文分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34472804/