I am using underscore.js library has a clone method.
var newObject = _.clone(oldObject);
I read from one of the comments that it’s a shallow clone. I want to make a clone of an object and pass it to different functions.
When i alter the newObject which is inside the function A(), i get the following results…
{
'Des': 'Some Des'
'Des1': 4,
'Des2': {
"ChildDes": 0,
},
},
But when i pass the newObject which is the clone object to an another function B(), i get alert value as [Object,Object]. Why? I am not able to print the value like this..
function B(newObject){
alert(newObject.Des2);
}
A “shallow copy” is a copy, that just copies all members. If one of the members is a reference to an object, than changes on the copied reference will effect the original one. A “deep copy” will copy the objects too, so that changes on deep copied elements won’t effect the original object.
Deep copies are sometimes hard to achieve since an objects member could have a reference on the object itself.
Play a little bit with different copy styles and see for yourself what can happen. See also: What does it mean to clone() an object?