我正在尝试将一些 JSON 加载到 JavaScript 类中,并将 JSON 中的一些属性分配给该类实例上的属性,但我在“this”和作用域方面遇到了问题。我很确定该解决方案涉及箭头函数,但我不知道如何将它们组合在一起。
这是我到目前为止所拥有的:
class Test {
constructor(url) {
this.loadJSON(url, this.init);
}
loadJSON(url, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.response);
}
};
xhr.send(null);
}
init(response) {
console.log(response.description);
// this is undefined
this.description = response.description;
}
}
在 init() 方法中,console.log 按我的预期工作,但我无法将任何内容分配给对象 - 我只是不断收到“这是未定义的”。
最佳答案
修改你的回调(xhr.response);代码如下:
callback.call(this, xhr.response);
或者,修改 this.loadJsON 代码,如下所示:
this.loadJSON(url, this.init.bind(this));
这是完整的解决方案:
class Test {
constructor(url) {
this.that = this;
this.loadJSON(url, this.init);
//Or, this.loadJSON(url, this.init.bind(this)); In that case you dont have to modify "callback(xhr.response);" code
}
loadJSON(url, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback.call(this, xhr.response);
}
};
xhr.send(null);
}
init(response) {
console.log(response.description);
this.description = response.description;
console.log(this.description);
}
}
let t = new Test('MY URL');
关于javascript - 如何通过回调和匿名函数将 'this' 保留在范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48998388/