我有一个CONTACT javascript对象。我调用CONTACT.load()来通过$ .ajax()读取CONTACT.id的数据。成功后,我可以使用ajax()调用返回的数据。然后我将一些读取数据保存在对象属性中。但是,保存的属性值将丢失。这是我的代码:
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 :(得分:0)
'this'指的是另一个对象。
timedelta