Rohit Jindal Rohit Jindal - 7 months ago 22
Javascript Question

AngularJS : copy vs extend

Explanation :

we come across some situation in which we need to copy one object to another object. In that case, we probably have two solutions: angular.copy() or angular.extend().

Challenge i am facing :

As we know

angular.copy(source, destination)
creates a deep copy of source object and assign it to destination. By writing deep copy, we mean that a new copy of the referred object is made and its working fine.

deep copy code :

var mySource = {'name' : 'Rohit', 'age' : '24'}
var myDest = {}
angular.copy(mySource,myDest);
mySource.name = "Jindal";
console.log(mySource); // Object {name: "Jindal", age: "24"}
console.log(myDest); // Object {name: "Rohit", age: "24"}
console.log(mySource.obj === myDest.obj); // false


Here, I modify the source object
mySource.name = "Jindal"
but it is not affecting the destination object
myDest
as expected.
If we check
mySource.obj === myDest.obj
, this will give false because both point to different objects.

Now,I am facing issue with
angular.extend(destination, source)
as it creates a
shallow copy
means in this both source and destination will point to same address.
So, if i will modify source object then it will also reflect in destination object. But it's not happening.


shallow copy code :

var mySource = {'name' : 'Rohit', 'age' : '24'}
var myDest = {}
angular.extend(myDest,mySource);
mySource.name = "Jindal";
console.log(mySource); // Object {name: "Jindal", age: "24"}
console.log(myDest); // Object {name: "Rohit", age: "24"}
console.log(mySource.obj === myDest.obj); // True


jsfiddle : https://jsfiddle.net/U3pVM/24322/

As i am new in this, need help to understand the proper flow of angular.copy() & angular.extend().

Any immediate help will be highly appreciable. Thanks

Answer

I updated the code . Now angular.extends works as you expected. Remember that if you pass angular.extends an empty object as first parameter (destination) and then the source, angular is going to preserve both objects and copy only the properties, just like angular.copy does.

// angular.copy()

var mySource = {'name' : 'sakshi', 'age' : '24', 'obj' :{'key':'value'}}
var myDest = angular.copy(mySource);

mySource.name = "Rohit";
console.log(mySource); // Object {name: "Rohit", age: "24", obj: Object}
console.log(myDest); // Object {name: "sakshi", age: "24", obj: Object}
console.log(mySource.obj === myDest.obj); // false

// angular.extend()

var mySource = {'name' : 'sakshi', 'age' : '24', 'obj' :{'key':'value'}}
var myDest = angular.extend(mySource);
mySource.name = "Rohit";
console.log(mySource); // Object {name: "Rohit", age: "24", obj: Object}
console.log(myDest); // Object {name: "sakshi", age: "24", obj: Object}
console.log(mySource.obj === myDest.obj); // True
Comments