我有一个带有变量“parentVar”的对象,我想将 ajax 请求的响应写入其中。 听起来很简单,但由于一些命名空间问题,我无法做到这一点。
我写了一个非常简单的例子,它显示了问题。
当我调用对象的初始化函数时,ajax 请求将启动:
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 调用执行 Ajax-Request 的函数“load”,并返回接收到的数据(在另一个回调函数中)。
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");
}
}
我已经尝试将范围传递给加载程序函数,然后在回调函数中取回它。但它没有用。
我还在初始化函数中尝试了“var parentscope = this;
”,
和“parentscope.parentVar = newData;
”——它也没有用。
是否可以通过将 parentVar 设为私有(private)来实现此目的? (我的意思是“var parentVar = 'old';
”而不是“this.parentVar = 'old';
”)。
最佳答案
传递给 load()
的回调函数没有您想要的 this
值。您调用该函数 this
的方式将是 window
。您可以按如下方式绑定(bind) 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/
Is it possible to achieve this with
parentVar
being private? (I meanvar parentVar = 'old';
instead ofthis.parentVar = 'old';
).
您可以在 Parent()
构造函数中使用一个私有(private)变量,它可以在构造函数中定义的所有方法中访问。但它不会可以通过 parentObj.parentVar
在外部访问,因此您必须添加一个 getter 方法。
在 Parent()
构造函数中使用私有(private) var self = this;
变量然后使用 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
关于javascript - 访问祖 parent 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20043652/