Extending Objects in Underscore


Underscore is a very nice library, it’s what Backbone JS is built on. What I’ve come to like about it is its ability to provide very helpful functions that let you more effectively work with sets of data.

Below is the code we’ve seen before, only slightly modified because we’re using Underscore’s extend function now.

And the output:

This is the exact same output as our Ext JS example. Since there’s nothing new, I can’t go on about too many differences, but I can, however, bring up another related function in Underscore, defaults.

The defaults method is interesting in that it works very similarly, but turns our familiar objects into something new that the others haven’t yet done.

And the output:

This one fills in missing properties and ignores any match applied after. Our start object was able to keep the id as 123, the count at 41 and so on. The second argument, more set the name property because it didn’t exit in start and finally the properties on extra already existed, so it had no effect on the final output.

The extend and defaults functions work almost opposite from each other, but are great to have side-by-side when you need them.

For more information: extend and defaults.

 

Extending Objects in Dojo