我構建了一個客戶端數據集以發佈到服務器。使用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
無關。
我錯過了什麼?
編輯:此示例來自一個更大的代碼塊,我試圖將其減少到最簡單的可能表達式。顯然,這不是一個功能性的代碼片段。
我猜這個問題是在getDataFromForm ...你可以分享代碼嗎? – Prestaul 2012-04-16 19:37:57
*「我錯過了什麼?」*不確定,但我們缺少的是代碼,它顯然會返回有關該對象的問題。僅供參考,對象本身從不復制到任務中。被複制的值是對該對象的引用。 – 2012-04-16 19:48:58
爲什麼你放棄了自己的問題? – 2012-04-17 00:03:23