0

我定义了一个这样的类:

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

我似乎这个对象已经改变了,我怎样才能调用/使用我在初始化中定义的变量?

4

1 回答 1

1

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);
          }
    });
},
于 2012-07-19T06:11:57.733 回答