Best practice for expanding objects in underscore.js

I know that expanding objects are executed using

_.extend(parent, child); 

method.

I saw different places on the network where people select objects in a special way in underscore.js

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

Why are they doing this?

+7
javascript extend relation
source share
3 answers

According to the underscore document, Api _.extend method -

 _.extend(destination, *sources) 

First example

 _.extend(parent, child); 

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

Second example

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

In case you do not want to modify the parent object and still want both properties to be parent and child. You can use this one. Here you distribute the parent and child to the new object.

+20
source share

Take this example:

 myConfig = { name: 'bob' } yourConfig = { name: 'sam' } _.extend(myConfig, yourConfig); 

Now myConfig gets off. I have overwritten the original value of myConfig.name and I can never return it.

To save myConfig and yourConfig , I need to combine both into a 3rd object:

 myConfig = { name: 'bob' } yourConfig = { name: 'sam' } sharedConfig = _.extend({}, myConfig, yourConfig); 
+5
source share

The underscore extension method overwrites the first argument passed to it. But in most cases you do not want this. You just need another object where the second is expanded using the method of the first.

So, you are passing an empty object as a container object for the result.

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

+2
source share

All Articles