Best practice to extend objects in underscore.js

Sebastian picture Sebastian · Mar 8, 2015 · Viewed 16.1k times · Source

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?

Answer

syed imty picture syed imty · Mar 8, 2015

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.