我有一个带有变量" parentVar"的对象,我想将ajax-request的响应写入其中。 听起来很简单,但由于一些命名空间问题,我无法做到这一点。
我写了一个非常简约的例子,它显示了问题。
当我调用Object的init函数时,将启动ajax-request:
var parentObj = new Parent();
//Do some work (I need some functionality from the object before it can be fully initialized)
alert("Old Value = " + parentObj.parentVar);
parentObj.init(function(){
alert("New Value = " + parentObj.parentVar);
});
init-Function调用Function" load"执行Ajax-Request,并返回接收到的数据(在另一个回调函数中)。
function Parent(){
this.parentVar = "old"; //this value should be replaced
this.init = function(initCallBack){
this.load(function(newData){ //load the content of the file
this.parentVar = newData; //write the content into the variable
initCallBack(); //I'm done!
});
}
this.load = function(callbackFunc){
//load the new value from a file via ajax (asyncron).
//When finished: call callbackFunc
callbackFunc("newValue");
}
}
我已经尝试将范围传递给loader-function,并将其返回到callBack-Function中。但它没有用。
我也试过" var parentscope = this;
"在init-Function中,
和" parentscope.parentVar = newData;
" - 它也没有用。
有可能在parentVar为私有的情况下实现这一目标吗? (我的意思是" var parentVar = 'old';
"而不是" this.parentVar = 'old';
")。
答案 0 :(得分:1)
问题是传递给init函数中的加载的回调中的this
不是引用Parent
对象而是引用window
对象。有一个众所周知的黑客:保存对this
中的父_this
的引用。其他常用的变量名称是that
和self
,所有这些都以更多下划线为前缀。这是一个有效的代码:
function Parent(){
this.parentVar = "old"; //this value should be replaced
var _this = this;
this.init = function(initCallBack){
this.load(function(newData){ //load the content of the file
_this.parentVar = newData; //write the content into the variable
initCallBack(); //I'm done!
});
}
this.load = function(callbackFunc){
//load the new value from a file via ajax (asyncron).
//When finished: call callbackFunc
callbackFunc("newValue");
}
}
答案 1 :(得分:1)
传递给load()
的回调函数没有您想要的this
值。您调用该函数this
的方式为window
。您可以按如下方式绑定this
的值:
this.load(function(newData){ //load the content of the file
this.parentVar = newData; //write the content into the variable
initCallBack(); //I'm done!
}.bind(this));
...然后它会起作用:http://jsfiddle.net/v9Hvb/
是否有可能在
parentVar
为私有的情况下实现此目的? (我的意思是var parentVar = 'old';
而不是this.parentVar = 'old';
)。
您可以在Parent()
构造函数中使用私有变量,并且可以在构造函数中定义的所有方法中访问它。但赢了可以通过parentObj.parentVar
在外面访问,因此您必须添加一个getter方法。
在var self = this;
构造函数中使用私有Parent()
变量会更容易,然后在方法中使用self
而不是this
:
function Parent(){
var self = this;
self.parentVar = "old"; //this value should be replaced
self.init = function(initCallBack){
self.load(function(newData){ //load the content of the file
self.parentVar = newData; //write the content into the variable
initCallBack(); //I'm done!
});
}
self.load = function(callbackFunc){
//load the new value from a file via ajax (asyncron).
//When finished: call callbackFunc
callbackFunc("newValue");
}
}
演示:http://jsfiddle.net/v9Hvb/1/
进一步阅读:MDN's this
article