从第一个对象创建的另一个对象中访问对象原型变量

Accessing an Object Prototype's variable from within another Object created by the first

本文关键字:一个对象 访问 对象 原型 变量 创建      更新时间:2023-09-26

我有一个创建异步XMLHttpRequest的对象。

它工作得很好,除了我想在请求的回调函数中访问变量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);
}
}

我没有测试过,但是这个呢:

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);
}
}