无法更新Object'中的Javascript Object属性;s函数调用

Unable to update Javascript Object property in Object's function call

本文关键字:Object 函数调用 Javascript 属性 中的 更新      更新时间:2023-09-26

我有一个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);  
}

控制台日志O/p是这样的:

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

请注意,当我在testtest()中再次设置CONTACT.city的值时,对象将保留属性值。有人能解释一下,为什么在调用testest()时CONTACT.city变为空?

"这个"指的是另一个对象。

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);
}