XMLHttpRequest inside an oject: how to keep the refrence to "this"

Posted by Julien on Stack Overflow See other posts from Stack Overflow or by Julien
Published on 2010-05-11T05:41:50Z Indexed on 2010/05/11 5:44 UTC
Read the original article Hit count: 246

Filed under:

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 obecjt anymore, so I don't have access to this.foo. Ho can I keep the reference to the main object inside XMLHttpRequest events?

© Stack Overflow or respective owner

Related posts about jaavscript