XMLHttpRequest inside an object: how to keep the reference 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
6:24 UTC
Read the original article
Hit count: 305
JavaScript
|AJAX
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?
© Stack Overflow or respective owner