来自对象的内部ajax调用正在清除成员变量

时间:2013-09-24 17:48:20

标签: javascript ajax oop

我有对象

var MyObject = (function (){

     var MyObject = function (a,b){
          this.A = a;
          this.B = b;
          this.C;


     }

     MyObject.prototype.PublicFunction = function(){

          var someVariable = 123; //this.A and this.B are both fine here.
          var self = this;
          $.ajax({
            type: "POST",
            url: "Default.aspx/PageMethod",
            data: "{" + args + "}",
            dataType: "json",
            async: true,
            cache: false,
            contentType: "application/json; charset=utf-8",
            success: function (data, status) {  
             //this.A = undefined, this.B = undefined, this.C = the data.
             self.C = data.d
             },
            error: function(xhr, status, error){

             alert('tears');



          }
       });
     }


return MyObject;
}());

当我输入原型函数this.A\B时,它们都是构造函数的值。执行ajax调用后this.A\B都是undefined。我不知道该怎么做。我可能不太了解我需要的对象的范围。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

与之前的问题类似,您的Success函数最有可能在没有上下文的情况下执行(因此它位于全局上下文中this == window

只需尝试在成功函数中记录thisconsole.log(this)) - 您将看到它是window对象。

您遇到的问题的常见解决方法是创建对this的本地引用,如下所示:

 MyObject.prototype.PublicFunction = function(){
     var self = this;
      var someVariable = 123; //this.A and this.B are both fine here.
      //AJAX HOOPLAH
      Success(data) {
          self.C = data.d

          //this.A = undefined, this.B = undefined, this.C = the data.
      }
      Fail{
        alert('tears');
      }

 }