Sergey Tyrtyshnikov Sergey Tyrtyshnikov - 1 month ago 6
Javascript Question

When I push to array, it pushes to another array also

This is JS:



angular.module('app', [])
.controller('fooCtrl', function($scope){
var fooProto = {
arrayItems: [],
addItem: function(){
var self = this;
self.arrayItems.push(new Date());
}
};
$scope.fooes = [];
$scope.foo1 = angular.extend({}, fooProto);
$scope.foo2 = angular.extend({}, fooProto);
});




CodePen with HTML:
http://codepen.io/qn0361/pen/vXQqPG

How to escape from that?
Thank you!

Answer

Because you have an object in which you have an array

 var fooProto = {
      arrayItems: [],
      addItem: function(){
        var self = this;
        self.arrayItems.push(new Date());
      }
    };

Array is a reference type.So when you copy your objects,it copies the properties, and if the property is a reference type, it copies the reference

$scope.foo1 = angular.extend({}, fooProto);

the $scope.foo1 gets the copy of the referenece, they all refer to the same object. So you work with the same object by two references,which refer to the same array.

You can fix it with constructor-function

function foo(){
   this.arrayItems = [];
   this.addItem = function(){
      this.arrayItems.push(new Date());
   }
}

var foo1 = new foo();
var foo2 = new foo();

Here you will have two instances of foo, each of them has it's own arrayItems.

In your case you don't need to copy items, as I understand you do that for not copying but creating a new instance of that 'type'.

Comments