5

To inherit properties of one object by another while dealing with JavaScript objects, I often see usage of _.clone where the intention was to create an object with another object's properties and then it would be extended.

Why can't we just use _.extend which is more relevant to extend an object?

Please tell me the difference between the two and why we can't _.extend instead of _.clone which is a costly operation.

André Dion
  • 21,269
  • 7
  • 56
  • 60
Madav
  • 311
  • 1
  • 5
  • 12

2 Answers2

5

_.extend mutates the object. _.clone creates a copy by values, not by reference and does not change the original object. Please note that _.extend is merely an alias for _.assignIn.

_.assignIn(object, [sources])

Note: This method mutates object.

https://lodash.com/docs/4.17.2#assignIn

Also see documenation for _.clone:

https://lodash.com/docs/4.17.2#clone

Community
  • 1
  • 1
connexo
  • 53,704
  • 14
  • 91
  • 128
  • _.extend mutates the actual object and _.clone returns a copy of the object. Rather, why can't we establish a parent-child (prototypal inheritence) relationship between the objects so that, if the child doesn't have a property, it will inherit from parent and provide. And by doing so, we can have so many childs and a parent rather than mutating/cloning the object. Please tell me. – Madav Dec 13 '16 at 14:04
4

If you _.extend() an existing object, you mutate the object. If you _.clone() it first, the original object remains untouched.

You could of course extend an empty object with the original object's properties and some additional ones, which also leaves the original object unchanged:

_.extend({}, originalObject, {
    additionalProperty: "foo"
})

This works very similar to a shallow clone of originalObject. With ES2015, you can achieve the same goal with plain JavaScript and Object.assign().


Additional reading:

Community
  • 1
  • 1
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
  • _.extend mutates the actual object and _.clone returns a copy of the object. Rather, why can't we establish a parent-child (prototypal inheritence) relationship between the objects so that, if the child doesn't have a property, it will inherit from parent and provide. And by doing so, we can have so many childs and a parent rather than mutating/cloning the object. Please tell me. – Madav Dec 13 '16 at 14:01