return a variable from a event listener
I have a generic function for XMLHttpRequests. as follows:
function XMLRequest(address, data){
this.html = "null";
this.xml = null;
this.stat = null;
req = new XMLHttpRequest();
req.addEventListener('readystatechange', function(this) {
console.log("from event listener, this.html = "+this.html);
this.ready = req.readyState;
if(req.readyState == 4)
{
this.stat = req.readyState;
if(req.status == 200)
{
try{
this.xml = req.responseXML.documentElement;
}
catch(err){
this.xml = err;
}
try{
this.html = req.responseText;
}catch(err){
this.html = err;
}
console.log("html = "+this.html);
}
}
}, false);
req.open("GET", address+"?"+data, true);
req.setRequestHeader('content-type', "text/xml");
req.send();
return this;
};
I made it with the idea that i would use the watch()
function to watch for a change in in this.html
or this.xml
. However, I never saw the change, and I realized why;
Inside of the anonymous listener function, this refers to the anonymous function, not XMLRequest
I was hoping to find a way around this, to somehow get the xml & text response out of the listener function and into the this.xml
& this.html
of the XMLRequest
function, so that I can then watch for it
Is there any way I can do that?
--edit--
Brad's example, with my edits, for discussion:
function MyObject(){
this.publicFoo = 'BAR';
var privateFoo = 'bar';
var self = this; // store current context so we can reference it in other scopes.
this.CallMe = function(){
self.publicFoo = 'newBAR';
开发者_如何转开发 setTimeout(function(){
alert('public: ' + self.publicFoo + '\nprivate: ' + privateFoo);
},100);
};
return this;
};
var myobj = MyObject();
myobj.CallMe();
alert(myobj.publicFoo) <-- I want this to alert "newBAR", not "BAR"
Store the variables you need before using them, then reference them (as you'd typically do to avoid scope problems:
function MyObject(){
this.publicFoo = 'BAR';
var privateFoo = 'bar';
this.CallMe = function(){
// set them as something referenceable when not within the object's scope
var iSee_publicFoo = this.publicFoo,
iSee_privateFoo = privateFoo;
setTimeout(function(){
alert('public: ' + iSee_publicFoo + '\nprivate: ' + iSee_privateFoo);
},100);
};
return this;
};
var myobj = MyObject();
myobj.CallMe();
Using the var self = this
version:
function MyObject(){
this.publicFoo = 'BAR';
var privateFoo = 'bar';
var self = this; // store current context so we can reference it in other scopes.
this.CallMe = function(){
setTimeout(function(){
alert('public: ' + self.publicFoo + '\nprivate: ' + privateFoo);
},100);
};
return this;
};
var myobj = MyObject();
myobj.CallMe();
精彩评论