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 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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With