gpt4 book ai didi

javascript - 从事件监听器返回一个变量

转载 作者:行者123 更新时间:2023-12-02 20:16:29 25 4
gpt4 key购买 nike

我有一个 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.htmlthis.xml< 中的更改。然而,我从未看到过变化,并且我意识到了原因;

在匿名监听器函数内部,this 指的是匿名函数,而不是 XMLRequest

我希望找到解决这个问题的方法,以某种方式将 xml 和文本响应从监听器函数中获取到 this.xmlthis.html XMLRequest 函数,以便我可以监视它

有什么办法可以做到这一点吗?

--编辑--

布拉德的示例,经过我的编辑,供讨论:

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();

关于javascript - 从事件监听器返回一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6235001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com