0

I have an Object that creates an Async XMLHttpRequest.

It is working nicely, except that I want to access the variable address in the callback function for the request. If I use this.address it doesn't work because this doesn't refer to the Async object anymore but to the XMLHttpRequest object created by my Async object. How can I step out of the XMLHttpRequest object to access Async's variables?

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);
}
}
Christopher Reid
  • 3,364
  • 2
  • 25
  • 63

1 Answers1

1

I didn't test it but how about this:

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);
}
}
webduvet
  • 4,006
  • 2
  • 25
  • 39