我有一个与此结构的类:
class MyClass{
json;
constructor(){
}
}
我想将我的" JSON"属性分配为构造函数中的API请求。
我尝试了各种方法,甚至直接从其他论坛中复制了代码片段。在调试器和console.log()
中,我已经确认我实际上得到了响应,在Promise.prototype.then()
中,我能够使用结果。但是我只是无法将其分配给类属性。
这些示例不起作用:
class MyClass{
json;
constructor(){
fetch(url)
.then(response => response.json())
.then(json => {
this.json = json; // I've tried using "self" when not using the "=>" operator
});
}
}
class MyClass{
json;
constructor(){
fetch(url)
.then(response => response.json())
.then(json => {
this._setJson(json);
});
}
_setJson(json){
this.json = json;
}
}
我还尝试过将json
初始化为数组,并使用this.json.push(json)
或将json
返回作为对象。所有时间this.json
从未分配,我得到ReferenceError: json is not defined↵ at eval (...
我希望分配它,但显然不是。另外,如果有任何区别,我正在使用Chrome 75。 - 谢谢
您的结构看起来略有关闭:
class MyClass{
constructor() {
this.json = null;
//fetch logic here
}
_setJson(json){
this.json = json
}
}
执行回调时,this
点指向全局范围而不是MyClass
范围。要解决此问题,请将对象的上下文保存到某些变量中,例如self
:
class MyClass {
json;
getJson() {
return this.json;
}
constructor(myCallback) {
var self = this;
fetch("https://www.mocky.io/v2/5185415ba171ea3a00704eed").then(function(response) {
return response.json().then(function(json) {
alert(this == myClassInstance); // false
alert(self == myClassInstance); // true
self.json = JSON.stringify(json);
myCallback();
});
});
}
}
var myCallBackImpl = () => { document.getElementById("response").innerHTML = myClassInstance.getJson(); }
var myClassInstance = new MyClass(myCallBackImpl);