Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest inside an object: how to keep the reference to "this"

I make some Ajax calls from inside a javascript object.:

myObject.prototye = {
  ajax: function() {
    this.foo = 1;

    var req = new XMLHttpRequest();
    req.open('GET', url, true);
    req.onreadystatechange = function (aEvt) {  
      if (req.readyState == 4) {  
        if(req.status == 200)  {
          alert(this.foo); // reference to this is lost
        }
      }
  }
};

Inside the onreadystatechange function, this does not refer to the main object anymore, so I don't have access to this.foo. Ho can I keep the reference to the main object inside XMLHttpRequest events?

like image 215
Julien Avatar asked May 11 '10 05:05

Julien


1 Answers

The most simple approach is usually to store the value of this on a local variable:

myObject.prototype = {
  ajax: function (url) { // (url argument missing ?)
    var instance = this; // <-- store reference to the `this` value
    this.foo = 1;

    var req = new XMLHttpRequest();
    req.open('GET', url, true);
    req.onreadystatechange = function (aEvt) {  
      if (req.readyState == 4) {  
        if (req.status == 200)  {
          alert(instance.foo); // <-- use the reference
        }
      }
    };
  }
};

I suspect also that your myObject identifier is really a constructor function (you are assigning a prototype property).

If that's the case don't forget to include the right constructor property (since you are replacing the entire prototype), which is simply a reference back to the constructor.

Maybe off-topic to this issue but recommended to read:

  • Constructors considered mildly confusing
like image 196
Christian C. Salvadó Avatar answered Oct 10 '22 01:10

Christian C. Salvadó