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变空了?