I've been poking around a bit, I'm not very into this world. And the doubt has arisen regarding the difference between =
and .copy()
.
I have found a couple of things in English, but I have not found any documentation in Spanish and I would find it interesting to have references in SOE.
Therefore, here is the question:
What is the difference between .copy()
and .extend()
in AngularJs?
There are normally two ways to copy objects
Shallow copy
Using the operator
=
a copy of this type is made, these copies make a replica of the same object, even copying the reference in memory, in such a way that both variables will share attributes and everything that you modify to one will affect both.Deep copy
With the
copy()
angular method or overwriting the methodclone()
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 other.UPDATE
.copy()
Makes a deep copy of an object, keeping the structure and format of the object, but creating a new pointer.
.extend()
It allows us to extend an object, that is, to create an object based on another/to add more objects to an existing one.
Let's imagine that we want to add certain methods and variables to the $scope, we would do for example:
The same could be done with the method
extends()
:We are extending the $scope object by adding the objects described above to it.
Note: If you look at the angular documentation itself , there is a note that says
Which means that it does not recursively join the objects, so if the objects with which you want to extend have other objects, no pointer is created for each of those objects, and therefore both objects will share the modifications (shallow copy).
Example:
jsfiddle
I hope it helps.