2013-09-24 18 views
1

我有對象內部AJAX調用結算成員變量

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。我不知道這裏要做什麼。我可能不瞭解我需要的對象的範圍。誰能幫忙?

+0

您可以加入更多的AJAX hooplah的? –

+0

保存爲 –

+1

您可以將成功函數綁定到'this'。 'function(data){...}。bind(this)' – Shmiddty

回答

2

你的問題類似早期,你的成功的功能是最有可能得到不利用上下文中執行(因此它是在全球範圍內,其中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'); 
     } 

}