简体   繁体   中英

Best practice to extend objects in underscore.js

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?

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.

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM