JustBasti JustBasti - 4 months ago 30
Javascript Question

Best practice to extend objects in underscore.js

I know that extending objects is done via the

_.extend(parent, child);


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?


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.