Reputation: 11
I've looked through the documentation and source code, and it appears that underscore's extend method _.extend
makes a shallow copy. One of the collaborators also said that the extend method does a shallow copy of the object "intentionally" here.
Now my question is : Why was it made that way ? Could you please provide me with some scenarios or use cases where this shallow copy would be better?
I tried to look for some answers and I couldn't find much about this except that "it's a good thing".
Upvotes: 0
Views: 269
Reputation: 4249
Deep copies or object clones are very computational expensive. _.extend
is essentially just an alias for _.assignIn(object, [sources])
which does pretty much the same as _.assign
but iterates over own and inherited source properties. The native ES6 Object.assign
does not iterate over inherited source properties.
Taking the example from lodash's documentation on assignIn
, Object.assign
would give you the following output:
function Foo() {
this.a = 1;
}
function Bar() {
this.c = 3;
}
Foo.prototype.b = 2;
Bar.prototype.d = 4;
console.log(Object.assign({ 'a': 0 }, new Foo, new Bar));
// { a: 1, c: 3 }
Whereas _assignIn
or _.extend
gives you
// { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
As you can see, also inherited source properties (set via the prototype), that is b
and d
, were also iterated.
If you want to deeply clone an object, you can use _.cloneDeep(value)
. But keep in mind that such deep clone is very computational expensive compared to a shallow copy.
Upvotes: 2