保持超越变量声明的对象引用

时间:2012-04-16 19:34:36

标签: javascript object reference

我正在构建一个客户端数据集合以发布到服务器。使用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每个按钮点击的新分配。每个click事件都是一个新的函数调用,newData(理论上)应该是一个新对象,与任何其他按钮点击的newData无关。

我错过了什么?

编辑:此示例来自更大的代码块,我尝试将其缩减为最简单的表达式。显然,原样,这不是一段功能代码。

1 个答案:

答案 0 :(得分:1)

听起来好像是在传递一个物体,并期待一个副本。

在JavaScript中,对象本身永远不会复制到赋值中。它是 by value 语言,但在Objects的情况下,复制的值是对象的引用。因此,从newData返回getDataFromForm将导致每个onClick中对同一对象的引用的副本。