Explaining Different Object Copy Methods :
When it comes to copying objects in certain situations, two common solutions are often considered: using angular.copy() or angular.extend().
Challenge I Am Currently Facing :
The
angular.copy(source, destination)
method creates a deep copy of the source object and assigns it to the destination. This means that modifications made to the source object do not affect the destination object.
Code for Deep Copy :
var mySource = {'name' : 'Beta', 'age' : '24'}
var myDest = {}
angular.copy(mySource,myDest);
mySource.name = "Alpha";
console.log(mySource); // Object {name: "Alpha", age: "24"}
console.log(myDest); // Object {name: "Beta", age: "24"}
console.log(mySource.obj === myDest.obj); // false
However, with
angular.extend(destination, source)
, a shallow copy is created where both source and destination point to the same address. Therefore, modifying the source will also reflect in the destination object, contrary to what might be expected.
Code for Shallow Copy :
var mySource = {'name' : 'Beta', 'age' : '24'}
var myDest = {}
angular.extend(myDest,mySource);
mySource.name = "Alpha";
console.log(mySource); // Object {name: "Alpha", age: "24"}
console.log(myDest); // Object {name: "Beta", age: "24"}
console.log(mySource.obj === myDest.obj); // True
For further reference, you can view this jsfiddle link: https://jsfiddle.net/U3pVM/24322/
If anyone could provide insight on the proper usage of angular.copy() & angular.extend(), it would be greatly appreciated as I am new to these concepts. Thank you.