从第一个创建的另一个Object中访问Object Prototype的变量

时间:2014-07-29 20:59:07

标签: javascript oop scope closures

我有一个创建Async XMLHttpRequest的Object。

它很好用,除了我想在请求的回调函数中访问变量address。如果我使用this.address它不起作用,因为this不再引用Async对象,而是引用我的Async对象创建的XMLHttpRequest对象。如何走出XMLHttpRequest对象来访问Async的变量?

function Async(address) {
this.req = new XMLHttpRequest();
this.address = address
}

Async.prototype = {

create: function() {
    this.req.open('GET', this.address, true);
    this.req.onreadystatechange = function(e) {
        if (this.readyState == 4) {
            if (this.status == 200) {
                dump(this.responseText);

//HERE IS WHERE THE ISSUE IS 

                console.log("loaded"+this.address)



            } else {
                dump("COULD NOT LOAD \n");
            }
        }
    }
    this.req.send(null);
}
}

1 个答案:

答案 0 :(得分:1)

我没有测试它但是怎么样:

function Async(address) {
this.req = new XMLHttpRequest();
this.address = address
}

Async.prototype = {

create: function() {

    var self = this; // ADD THIS LINE

    this.req.open('GET', this.address, true);
    this.req.onreadystatechange = function(e) {
        if (this.readyState == 4) {
            if (this.status == 200) {
                dump(this.responseText);

//HERE IS WHERE THE ISSUE IS 

                console.log("loaded"+self.address)



            } else {
                dump("COULD NOT LOAD \n");
            }
        }
    }
    this.req.send(null);
}
}