我定义了这样一个类:
var LoadingPolecy={
initialize:function(){
return function(){
this.initialize.apply(this,arguments);
}
}
}
var AjaxLoadingPolecy= LoadingPolecy.initialize();
AjaxLoadingPolecy.prototype={
initialize:function(name){
this.name=name;
},
AjaxStartPolecy : function(){
...
},
AjaxStopPolecy : function(){
...
},
SetName : function(name){
...
}
}
var TempLoadingPolecy=LoadingPolecy.initialize();
TempLoadingPolecy.prototype={
initialize:function(displayArea,source,data){
this.loadingMsgPolecy = new AjaxLoadingPolecy();
...
},
StartLoadingTempPolecy : function(callback){
this.loadingMsgPolecy.SetName('view');
this.loadingMsgPolecy.AjaxStartPolecy();
var a = $.ajax({
...
success:function(html){
callback(html);
}
});
},
EndLoadingTempPolecy : function(html){
//Cannot call method 'AjaxStopPolecy' of undefined error
this.loadingMsgPolecy.AjaxStopPolecy();
....
}
}
我似乎已经更改了其中的对象,我如何调用/使用我在初始化中定义的变量?
ajax成功回调(大多数其他回调也是如此)不会给您相同的this
。但是,您可以将this
的前一个副本保存到另一个变量中,并以这种方式访问它:
我不明白你问的是代码的哪一部分,但这里有一个简单的例子,你可以从中进行调整:
initialize:function(displayArea,source,data){
StartLoadingTempPolecy : function(callback) {
this.loadingMsgPolecy.SetName('view');
this.loadingMsgPolecy.AjaxStartPolecy();
// save copy of `this` for future use in the success handler
var self = this;
var a = $.ajax({
...
success:function(html) {
// you can use the variable `self` here to access the previous this ptr
callback(html);
}
});
},