Reputation: 1347
I am studying angularjs and have issue over usage of copy and merge function provided by angular library. According to documentation, copy creates a deep copy of source while merge deeply extends the destination object by copying own enumerable properties from the source object.
Google only gives copy vs extend or merge vs extend. All I can find is the concept of deep copy and deep extend recursively. What's the difference between these two? Which is preferred over another?
I have created plunker and both have same output.
https://plnkr.co/edit/CORt259oczKwpBzh7cNH?p=preview
This is snippet having controller part:
<script type="text/javascript">
var app= angular.module("myapp",[]);
app.controller("myctrl",[function(){
var self = this;
self.obj={
val1: 'val1',
val2: 'val2',
val3: [{a:12, b:13}],
val4: {c:23, d:56}
};
self.secobj={};
self.thobj={};
self.forobj={};
self.changeVal = function(){
angular.copy(self.obj, self.secobj);
angular.extend(self.thobj, self.obj);
angular.merge(self.forobj, self.obj);
self.obj.val1 = 'value 1';
self.obj.val2 = 'value 2';
self.obj.val3[0].a = 11223;
self.obj.val3[0].b = 22334;
self.obj.val4.c = 1000;
self.obj.val4.d = 5555;
};
}]);
</script>
Upvotes: 1
Views: 849
Reputation: 1347
I saw source code of angularjs available at github to get more insight on this.
Angular.copy simply makes clone of object from source to destination. In that process, it deletes all objects from destination object and then copy properties from source.
On the other hand merge appends the source object to destination. Thus, if destination object already has some elements, it will remain there and new properties from source object will add to destination object. Moreover, merge supports multiple source object which can append themselves to destination object.
Upvotes: 3