2012-04-16 21 views
-1

我構建了一個客戶端數據集以發佈到服務器。使用Add按鈕的onClick事件,我收集表單數據並將其存儲在內部數組中。這是一些人爲/示例代碼來試圖證明這個問題(不幸的是,我無法分享源代碼)。對象引用持久超越變量聲明

var getDataFromForm = (function() { 
    var _internal = {}; /* Based on feedback, I think this is the reason for the behavior I'm experiencing */ 
    return function() { 
     var form = {}; 
     /* Get the form data */ 
     _internal.name = form.name; 
     _internal.id = form.id; 
     return _internal; 
    }; 
}()); 

var internal = { vals: [] }; 

function onClick() { 
    var newData = getDataFromForm(); 

    doAjaxValidation({ 
     success: function() { 
      internal.vals.push(newData); /* All values in array have been updated to this newData reference on click */ 
      internal.vals.push(JSON.parse(JSON.stringify(newData))); /* ugly, but the reference is broken and future clicks work as expected */ 
      internal.vals.push($.extend({}, newData)); /* reference to the object is still persisted through jQuery's extend */ 
     } 
    }); 

} 

我很困惑,爲什麼newData參考交給的newData每個按鈕單擊新任務。每個點擊事件都是一個新的函數調用,並且newData(理論上)應該是一個新的對象,與任何其他按鈕點擊中的newData無關。

我錯過了什麼?

編輯:此示例來自一個更大的代碼塊,我試圖將其減少到最簡單的可能表達式。顯然,這不是一個功能性的代碼片段。

+1

我猜這個問題是在getDataFromForm ...你可以分享代碼嗎? – Prestaul 2012-04-16 19:37:57

+1

*「我錯過了什麼?」*不確定,但我們缺少的是代碼,它顯然會返回有關該對象的問題。僅供參考,對象本身從不復制到任務中。被複制的值是對該對象的引用。 – 2012-04-16 19:48:58

+0

爲什麼你放棄了自己的問題? – 2012-04-17 00:03:23

回答

1

聽起來好像你傳遞一個對象,並期待一個副本。

在JavaScript中,對象本身從不復制到任務中。這是一個的值語言,但對於對象而言,複製的值是對該對象的引用。因此,從getDataFromForm返回newData將導致對每個onClick中同一對象的引用副本。

+0

太棒了!你有鏈接到JavaScript中變量聲明/賦值的文檔嗎? – Christopher 2012-04-17 01:29:45

+0

@Christopher:對不起,但我沒有任何專門處理這個問題的文檔。有關一些常規信息,您可能需要查看https://developer.mozilla.org/en/JavaScript/Guide。它們確實包含特定於Mozilla的功能,但我認爲它們通常將它們記錄爲這樣。 – 2012-04-17 02:14:50

+1

沒有問題。我們一直在通過引用/通過JavaScript中與價值相關的錯誤來解決問題。 http://objrefnotset.blogspot.com/2012/02/javascript-object-and-variable-scope.html。我很欣賞你的洞察力。 – Christopher 2012-04-17 02:27:25