问题描述
|
我有一个XMLHttpRequests的通用函数。如下:
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;
};
我的想法是,我将使用watch()
函数来监视this.html
或this.xml
中的变化。但是,我从未看到过这种变化,并且意识到了原因。
在匿名侦听器函数内部,这是指匿名函数,而不是“ 4”
我希望找到解决此问题的方法,以某种方式使xml和文本响应从侦听器函数中移入XMLRequest
函数的this.xml
和ѭ2,中,以便我可以对其进行监视
有什么办法可以做到吗?
- 编辑 -
布拉德的例子,经我的编辑,供讨论:
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\"
解决方法
在使用它们之前,请先存储所需的变量,然后对其进行引用(通常可以这样做,以避免出现范围问题:
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();
使用var self = this
版本:
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();