gpt4 book ai didi

JavaScript 面向对象编程 : running two instances of a method within a single Object simultaneously

转载 作者:行者123 更新时间:2023-12-03 12:09:34 25 4
gpt4 key购买 nike

因此,我有一个对象 Async,它创建对(在本例中)来自 github 的 JSON 对象的请求。

有一个方法Async.createList,它可以从 github JSON 对象创建特定属性的所有实例的列表。当调用一次 Async.createList 时,它工作得很好,但我希望能够从同一请求的不同目标属性创建多个列表,这就是它失败的地方。

理想情况下,列表将附加到 Async.lists 对象,以便可以在 Async 对象之外使用它们。现在,当我多次调用 Async.createList 时,只有最后一次调用会附加到 Async.lists 中。

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

最佳答案

每次调用 github.createList 时,您都会重新分配 this.req.onload 的函数。

我知道您想在使用 req.onload 加载请求后执行操作,但您每次都分配一个新函数,因此将调用最后分配的函数。

您需要删除Async.createList中的onload函数

仅在请求加载后调用github.createList("name");,如下所示

var github = new Async("https://api.github.com/users/john/repos")

github.create();

github.req.onload = function () {

github.createList("name");
github.createList("id");
}

关于JavaScript 面向对象编程 : running two instances of a method within a single Object simultaneously,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25028133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com