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?
The most simple approach is usually to store the value of
thison a local variable:I suspect also that your
myObjectidentifier is really a constructor function (you are assigning aprototypeproperty).If that’s the case don’t forget to include the right
constructorproperty (since you are replacing the entireprototype), which is simply a reference back to the constructor.Maybe off-topic to this issue but recommended to read: