对象引用超越变量声明

时间:2021-11-07 11:06:45

I'm building up a client-side collection of data to post to a server. Using the onClick event of an Add button, I'm collecting the form data and storing it in an internal array. This is some faux/sample code to try to demonstrate the issue (I can't share the source, unfortunately).

我正在构建一个客户端数据集合以发布到服务器。使用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 */
       }
   });

}

I'm confused as to why the newData reference is handed to the new assignment of newData each button click. Each click event is a new function call and newData (theoretically) should be a new object which is not related to the newData from any other button click.

我很困惑为什么每次点击按钮都会将newData引用传递给newData的新赋值。每个click事件都是一个新的函数调用,newData(理论上)应该是一个新对象,它与任何其他按钮点击的newData无关。

What am I missing?

我错过了什么?

Edit: this sample is from a much larger block of code, and I tried to reduce it to the simplest possible expression. Obviously, as-is, this is not a functional piece of code.

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

1 个解决方案

#1


1  

It sounds as though you're passing an object,and expecting a copy.

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

In JavaScript, objects themselves are never copied in an assignment. It's a by value language, but in the case of Objects, the value that is copied is the reference to the object. So returning newData from getDataFromForm will result in a copy of the reference to the same object in each onClick.

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

#1


1  

It sounds as though you're passing an object,and expecting a copy.

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

In JavaScript, objects themselves are never copied in an assignment. It's a by value language, but in the case of Objects, the value that is copied is the reference to the object. So returning newData from getDataFromForm will result in a copy of the reference to the same object in each onClick.

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