簡體   English   中英

JavaScript OOP:在單個Object中同時運行方法的兩個實例

[英]JavaScript OOP : running two instances of a method within a single Object simultaneously

所以,我有一個對象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加載請求后執行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");
}

答案很簡單。 所有我需要做的是擺脫了onload中的功能Async.createList和簡單的調用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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM