10

I know that extending objects is done via the

_.extend(parent, child);

method.

I've seen different places in the web where people are extending objects in a special way in underscore.js

_.extend({}, this, child);

Why do they do that?

Sebastian
  • 1,593
  • 4
  • 26
  • 41

3 Answers3

25

According to the underscore documentation, The api of _.extend method is

_.extend(destination, *sources) 

First Sample

_.extend(parent, child);

In this sample code, you are actually extending the properties from child object to parent object. Here the parent object is modified.

Second Sample

_.extend({}, parent, child);

In case you don't want to modify the parent object, and still want both the properties from parent and child. You can use this one. Here you are extending parent object, and child object to a new object.

TryingToImprove
  • 7,047
  • 4
  • 30
  • 39
syed imty
  • 1,018
  • 1
  • 9
  • 27
  • So if I use the first approach multiple times with different children, I'll have a parent having all the functionality of those different children. Right? Same thing with the second approach gives me whole different objects. – Sebastian Mar 08 '15 at 15:59
  • you dont have to call multiple times, you can have n of arguments. U can do something like _.extend(parent,child1,child2,chilld3,child4);. So parent will have all properties of child1,2,3 and 4 – syed imty Mar 08 '15 at 16:52
7

Take this example:

myConfig = { name: 'bob' }

yourConfig = { name: 'sam' }

_.extend(myConfig, yourConfig);

Now, myConfig is clobbered. I've overwritten the original value of myConfig.name, and I can never get it back.

In order to preserve myConfig and yourConfig, I need to combine both into a 3rd object:

myConfig = { name: 'bob' }

yourConfig = { name: 'sam' }

sharedConfig = _.extend({}, myConfig, yourConfig);
user229044
  • 232,980
  • 40
  • 330
  • 338
3

Underscore's extend method overwrites the first argument passed to it. But most of the times you don't want that. You just want another object where the second is extended with method of the first.

So you pass an empty object as the container object for the result.

var grandChild = _.extend({}, parent, child);

Mukesh Soni
  • 6,646
  • 3
  • 30
  • 37