簡體   English   中英

通過AJAX分配和使用javascript對象屬性

[英]Assign and use javascript object property via AJAX

所以我有這個Javascript對象:

var obj = { 
    conn : null,
    first : function(thisIdentity) {
        "use strict";
        $(document).on('click', thisIdentity, function(e) {
        e.preventDefault();
        $.ajax ({ 
            url : some value,
            // other parameters
            success : function() {
                this.conn = new Connection(data.user_id, "127.0.0.1:80");
            }
        });
   },
    second : function(thisIdentity) {
        "use strict";
        $(document).on('click', thisIdentity, function(e) {
            e.preventDefault();
            $.ajax ({ 
                url : some value,
                // other parameters
                success : function() { 
                    // using this.conn now results in UNDEFINED
                }
            });
    }
};

現在基本上將值分配給第一個函數的AJAX調用中的conn變量,但是當我嘗試在第二個函數中使用相同的值時,它指出this.conn是未定義的 我只想知道如何為對象的屬性分配值,並保留它以備將來使用? 謝謝!

在ajax成功回調中, this引用與原始對象的作用域不同。

將您的代碼更改為此:

var obj = { 
conn : null,
first : function(thisIdentity) {
    "use strict";
    var mySelf = this;
    $(document).on('click', thisIdentity, function(e) {
    e.preventDefault();
    $.ajax ({ 
        url : some value,
        // other parameters
        success : function() {
            mySelf.conn = new Connection(data.user_id, "127.0.0.1:80");
        }
    });
},
second : function(thisIdentity) {
    "use strict";
    var mySelf = this;
    $(document).on('click', thisIdentity, function(e) {
        e.preventDefault();
        $.ajax ({ 
            url : some value,
            // other parameters
            success : function() { 
                // now you can access the connection with mySelf.conn
            }
        });
    }
};

語法本身是錯誤的。 您正在創建變量或在對象文字內給出表達式。 請記住,這不是一個函數,而應該是:

$.ajax ({ 
    // computation and in success function 
    conn: new Connection(data.user_id, "127.0.0.1:80")
});

更新

當您給出這種定義方式時:

success : function() {
    this.conn = new Connection(data.user_id, "127.0.0.1:80");
}

在此, this對象是指success函數,而不是您的object 閱讀了解JavaScript中的范圍和上下文 現在,你需要創建一個代理變量this並使用它:

first : function(thisIdentity) {
    "use strict";
    var myObj = this;
    $(document).on('click', thisIdentity, function(e) {
    e.preventDefault();
    $.ajax ({ 
        url : some value,
        // other parameters
        success : function() {
            myObj.conn = new Connection(data.user_id, "127.0.0.1:80");
        }
    });
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM