我在下面有一个类设置,但事情大部分都有效,但是当调用json.onjload时,我在控制台声明中一直出现错误" Uncaught TypeError: Cannot read property of 'push' of undefined
"
如何解决此错误?
var Clazz = new function(){
this.library = [];
this.add_library = function(file){
var json = new XMLHttpRequest();
json.overrideMimeType("application/json");
json.open("GET", file, false); //needs to be synchronise
json.onload = function(){
this.library.push(JSON.parse(json.responseText));
do something...
};
json.send(null);
};
}
Clazz.add_library("path/file.json");
解决方案
将this.library.push(...);
更改为Clazz.library.push(...);
答案 0 :(得分:0)
因为范围在this.add_library
var Clazz = new function(){
this.library = [];
var that = this;
this.add_library = function(file){
var json = new XMLHttpRequest();
json.overrideMimeType("application/json");
json.open("GET", file, false); //needs to be synchronise
json.onload = function(){
console.log(that)
that.library.push(JSON.parse(json.responseText));
//do something...
};
json.send(null);
};
}
new Clazz.add_library("path/file.json");
答案 1 :(得分:0)
尝试:
var Clazz = new function(){
this.library = [];
this.add_library = (file) => {
var json = new XMLHttpRequest();
json.overrideMimeType("application/json");
json.open("GET", file, false); //needs to be synchronise
json.onload = () => {
this.library.push(JSON.parse(json.responseText));
do something...
};
json.send(null);
};
}
或者您必须使用函数.bind(this)
,因为您在函数范围内对this
的可见性有疑问。
答案 2 :(得分:0)
你遇到的问题是上下文。基本上,JavaScript有this
的几种不同情况,您的示例使用其中两种:
this
是指使用方法的对象。this
引用全局对象或undefined
中的strict mode
。让我们看看您的代码(我会稍微调整您的代码以获得更多说明):
var Clazz = { // this code does the very same thing as `new function()`
library: [],
add_library: function(file){
// here if you use `this.library`, you would refer to the `library` field
// and the code works perfectly fine, because `this` refers to the object Clazz
json.onload = function(){
this.library.push(JSON.parse(json.responseText));
// ...on the other hand here `this` refers to the global object,
// because `json.onload` is a function, even though it is inside a method `add_library`
};
};
}
如何解决这个问题?有几种方法:
使用.bind()
:
json.onload = function(){
this.library.push(JSON.parse(json.responseText));
}.bind(Clazz);
将上下文分配给变量:
const self = this;
json.onload = function(){
self.library.push(JSON.parse(json.responseText));
}
使用箭头功能:
json.onload = () => {
this.library.push(JSON.parse(json.responseText));
}