JavaScript OOP:在单个对象中同时运行一个方法的两个实例
因此,我有一个对象JavaScript OOP:在单个对象中同时运行一个方法的两个实例,javascript,json,oop,xmlhttprequest,prototype,Javascript,Json,Oop,Xmlhttprequest,Prototype,因此,我有一个对象Async,它从github创建一个JSON对象请求(在本例中) 有一个方法Async.createList,它从github JSON对象创建特定属性的所有实例的列表。只要调用一次Async.createList,它就可以正常工作,但我希望能够从同一请求的不同目标属性创建多个列表,这就是它失败的地方 理想情况下,列表将附加到Async.lists对象,以便它们可以在Async对象之外使用。现在,当我多次调用Async.createList时,只有最后一次调用附加到Async.
Async
,它从github创建一个JSON对象请求(在本例中)
有一个方法Async.createList
,它从github JSON对象创建特定属性的所有实例的列表。只要调用一次Async.createList
,它就可以正常工作,但我希望能够从同一请求的不同目标属性创建多个列表,这就是它失败的地方
理想情况下,列表将附加到Async.lists
对象,以便它们可以在Async
对象之外使用。现在,当我多次调用Async.createList
时,只有最后一次调用附加到Async.list
function Async(address) {
this.req = new XMLHttpRequest();
this.address = address
}
Async.prototype = {
lists : {},
create : function(callback) {
var self = this;
this.req.open('GET', this.address, true);
this.req.onreadystatechange = function(e) {
if (this.readyState == 4) {
if (this.status == 200) {
dump(this.responseText);
if (callback != null) callback()
} else {
dump("COULD NOT LOAD \n");
}
}
}
this.req.send(null);
},
response : function(json) {
return json == true ? JSON.parse(this.req.responseText) : this.req.responseText
},
createList : function(target) {
var self = this
var bits = []
this.req.onload = function(){
var list = self.response(true)
for(obj in list){
bits.push(self.response(true)[obj][target])
}
self.lists[target] = bits
}
},
}
我正在创建对象并调用如下方法:
var github = new Async("https://api.github.com/users/john/repos")
github.create();
github.createList("name");
github.createList("id");
然后尝试:
github.lists
答案非常简单。我所需要做的就是去掉
Async.createList
中的onload
函数和Async.createList
回调中的简单调用Async.create
createList : function(target) {
var self = this
var bits = []
var list = self.response(true)
for(obj in list){
bits.push(self.response(true)[obj][target])
}
self.lists[target] = bits
},
使用此命令实例化:
var github = new Async("https://api.github.com/users/john/repos")
github.create(callback);
function callback(){
github.createList("name");
github.createList("id");
}
每次调用
github.createList
时,您都在为this.req.onload
重新分配函数
我知道您希望在使用req.onload
加载请求后执行操作,但您每次都分配一个新函数,因此将调用最后分配的函数
您需要删除Async.createList
调用github.createList(“名称”)代码>仅在加载请求后,如下所示
var github = new Async("https://api.github.com/users/john/repos")
github.create();
github.req.onload = function () {
github.createList("name");
github.createList("id");
}
这与我给出的答案非常相似,但略有不同!看看我的。如果您提到我需要删除Async.createList
中的onload函数,我将接受您的回答。