1

我有对象

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. 我不确定在这里做什么。我可能不了解我需要的对象的范围。任何人都可以帮忙吗?

4

1 回答 1

2

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

只需尝试在您的成功函数中记录this( console.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');
      }

 }
于 2013-09-24T17:52:14.910 回答