Difference between .copy () and .extend ()

3

I've been snooping a little, I'm not very into this world. And the question has arisen regarding the difference between = and .copy() .

I have found a couple of things in English, but I have not found docu in Spanish and it would be interesting to have references in SOE.

Therefore, here I leave the question:

What is the difference between .copy() and .extend() in AngularJs?

    
asked by GDP 03.08.2017 в 09:40
source

1 answer

3

There are usually two ways to copy objects

Shallow copy

Using the = operator makes a copy of this type, these copies make a replica of the same object, copying even the reference in memory, so both variables will share attributes and everything that you modify to one will affect at two.

Deep copy

With the method copy() of angular or overwriting the method clone() in java correctly or in any language, a replica of the same object is made but a new memory pointer is generated in such a way that they have the same structure and information, but having different pointers, the changes are independent of each one.

UPDATE

.copy ()

Perform a deep copy of an object, maintaining the structure and format of the object, but creating a new pointer.

.extend ()

It allows us to extend an object, that is, create an object based on another / s or add more objects to an existing one.

Imagine that we want to add certain methods and variables to the $ scope, for example:

$scope.thingOne = ‘one’;
$scope.thingTwo = ‘two’;
$scope.getThings = function() { 
    return $scope.thingOne + ‘ ‘ + $scope.thingTwo; 
};

The same could be done with the extends() method:

angular.extend($scope, {
        thingOne: ‘one’,
        thingTwo: ‘two’,
        getThings: function() { 
            return $scope.thingOne + ‘ ‘ + $scope.thingTwo; 
        }
    });

We are extending the $ scope object by adding the objects described above.

Note: If you look at the angular documentation , there is a note that says

  

Note: Keep in mind that angular.extend does not support recursive merge (deep copy). Use angular.merge for this.

Which means that it does not make recursive union of the objects, so if the objects with which you want to extend have other objects in turn, no pointer is created for each of those objects, and therefore both objects they will share the modifications (surface copy).

Example:

//Arrays para extender
var array=['a','b','c'];
var array2=['d','e','f'];

//El objeto que sera enxtendido
var obj={}

//Extendemos obj, añadiendole los arrays
angular.extend(obj,{array,array2});

//Si eliminamos el primer elemento del array 
array.splice(0, 1);
//Y consultamos el array del objeto. 
//veremos que tambien se ha borrado el primer elemento
console.log(obj);

jsfiddle

I hope it helps.

    
answered by 03.08.2017 / 09:54
source