【发布时间】:2011-09-23 16:03:46
【问题描述】:
您好,我开始使用单例 javascript 设计模式,但我遇到了一些范围问题。在这里,我只是在试验一个小型 ajax,检索和存储单例。 从单例中的一个函数中,我调用另一个函数(this.ready,在 ajax 检索并存储数据时调用)但似乎“this”不是指单例,而是指“Object #XMLHttpRequest”根据 chrome 调试器,firefox 只是说它是未定义的。
var mag = {
magObj: [], // object to store the retrieved json data
getData: function(){
request = getHTTPObject(), // defined externally
request.onreadystatechange = this.setData;
request.open("POST", "be.php", true);
request.send(null);
},
setData: function(){
if (request.readyState == 4)
{
this.magObj = JSON.parse(request.responseText);
this.ready(); // this line yields the error, seems "this" does not refer to the singleton
}
else if (request.readyState == 1)
{
}
},
ready: function() {
console.log('ready');
},
construct: function(){
this.getData();
},
}
另外,如果我尝试将 getHTTPObject() 声明为顶部的单例变量,而不是使用全局变量,我会收到错误 无法读取未定义的属性“readyState”。即使我将它设置在顶部,它仍然是“this”getHTTPObject 似乎未定义:
var mag = {
magObj: [],
request: getHTTPObject(),
getData: function(){
this.request.onreadystatechange = this.setData;
this.request.open("POST", "be.php", true);
this.request.send(null);
},
setData: function(){
if (this.request.readyState == 4) // debugger says this.request is undefined
{
this.magObj = JSON.parse(this.request.responseText);
}
else if (this.request.readyState == 1)
{
}
},
construct: function(){
this.getData();
},
}
【问题讨论】:
-
"this" 根据调用函数在 javascript 中发生变化。看看这个答案stackoverflow.com/questions/4886632/…
标签: javascript scope this