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.
Oh hey, I'm a Senior Consultant for Headspring in Austin, TX. I've been working in software professionally since 2006 and I really, really love it. I'm mostly in the Microsoft world, but enjoy building computer things of all sorts (to be vague). When I'm not slinging code, I'm probably out and about slinging discs, bowling balls, or good beer with great friends.
You’re missing an important semantic here – _.extend modifies the first object you pass it. So after you call _.extend(start, more, extra), the start object has changed. In fact, start is the object that is returned. Your example makes it look like start isn’t modified.
http://www.facebook.com/mike.dilorenzo.3 Mike DiLorenzo
jQuery’s extend does a deep copy of nested objects. Underscore’s shallow copy of nested attributes can lead to some very subtle bugs. Take a look at the following article for a good discussion of the issue:
Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1205