2016-07-25 86 views
0

我有一個CONTACT JavaScript對象。我調用CONTACT.load()通過$ .ajax()讀取CONTACT.id的數據。成功時,我可以使用ajax()調用返回的數據。然後我將一些讀取的數據保存在對象屬性中。但是,保存的屬性值會丟失。這裏是我的代碼:無法更新對象函數調用中的Javascript對象屬性

var CONTACT= 
{ 
id: 1, 
referrals_loaded: false, 
city: '', 
}; 



CONTACT.load = function(cb) 
{ 
$.ajax({ 
     type: "POST", 
     url: "contactAjax.php", 
     data: { 
      ContactID: this.id, 
      actionID: 'LOAD_CONTACT_DATA', 
     }, 
     dataType: "json", 
     success: function(data) { 
      success = true; 
      var address = data['address']; 
      var addr = address[0]; 

      this.city = addr['city'].trim(); 
      console.log("City (in ajax()):" +this.city); 
      var province = addr['province'].trim(); 
      // ... 


      if (typeof cb==='function') (cb)(); 
     }, 
     error: function() { 

      alert("Could not load Contact data through LOAD_CONTACT_DATA ."); 
     } 
    }); 

console.log("City (after ajax()):" +this.city); 

} 

我的調用代碼是這樣的:

CONTACT.id = 123456; 
CONTACT.load('testtest'); 

function testtest() { 
    console.log("Contact city is " + CONTACT.city); 
    CONTACT.city = "London"; 
    console.log("Contact city is " + CONTACT.city); 
} 

而且執行console.log O/P是這樣的:

City (in ajax()):MARKHAM 
Contact city in testtest() 
Contact city is London 

注意,當我設置在testtest()中再次爲CONTACT.city的值,對象保留屬性值。有人能解釋一下,爲什麼當testest()被調用時,CONTACT.city變空了?

回答

0

'這'指的是一個不同的對象。

CONTACT.load = function(cb) 
{ 
var self = this; // common hack 
$.ajax({ 
     type: "POST", 
     url: "contactAjax.php", 
     data: { 
      ContactID: this.id, 
      actionID: 'LOAD_CONTACT_DATA', 
     }, 
     dataType: "json", 
     success: function(data) { 
      success = true; 
      var address = data['address']; 
      var addr = address[0]; 

      self.city = addr['city'].trim(); // <-- assign to correct object 
      console.log("City (in ajax()):" +this.city); 
      var province = addr['province'].trim(); 
      // ... 


      if (typeof cb==='function') (cb)(); 
     }, 
     error: function() { 

      alert("Could not load Contact data through LOAD_CONTACT_DATA ."); 
     } 
    }); 

console.log("City (after ajax()):" +this.city); 

}