There is a code:

<script> function MyObject(name){ this.name = name; } var arr = new Array(); var my = new MyObject(); my.name = "1"; arr.push(my); my.name = "2"; arr.push(my); for (var i = 0; i < arr.length; i++){ console.log(arr[i]); } </script> 

falls into the log:

enter image description here

and it was expected that various objects with names 1 and 2 would be added to the array. What is the reason for such behavior and how to fix it?

  • "different objects" - why? An object variable is a reference to an object; changing its properties, you do not create new objects. - Igor
  • @Igor, everyone realized his mistake. This transition from the C ++ language affects. - perfect
  • PS I thought that the copy gets into the array - perfect

1 answer 1

In JavaScript, all objects are assigned and passed by reference. As a consequence, performing:

 arr.push(my); 

you are not adding an object, but a link to it. All subsequent changes to the object contained in the variable my will affect the object that already lies in the array. This is how reference data types work.