Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why pass an empty object to jQuery's extend method?

jQuery has a very neat extend method, which merges 2 objects into one.

On the jQuery Plugins authoring page they show an example as follows:

var settings = $.extend({
    'location'         : 'top',
    'background-color' : 'blue'
}, options);

However, I've seen many plugins pass an empty object as the first parameter, like so:

var settings = $.extend({}, {
    'location'         : 'top',
    'background-color' : 'blue'
}, options);

As far as I can tell, these two do the exact same thing. The only difference would be if the defaults would have been stored in its own variable:

var defaults = {
    'location'         : 'top',
    'background-color' : 'blue'
},
settings = $.extend({}, defaults, options);

This way, you can always access your defaults without them being overridden by the options.


Here's the question: Why do so many plugin authors opt to pass an empty object to extend, even when they don't store the defaults in a variable?

Am I missing something?

like image 380
Joseph Silber Avatar asked Mar 11 '12 20:03

Joseph Silber


1 Answers

Extend is a very useful function to copy objects.

For example consider this:

foo = {'foo':'a'}
f = foo
f.foo = 'hello'
console.log(f)
    Object {foo="hello"}
console.log(foo)
    Object {foo="hello"}

f = $.extend({},foo)
f.foo = 'hello world'
console.log(f)
    Object {foo="hello world"}
console.log(foo)
    Object {foo="hello"}

So as you can see $.extend actually copied the object.

EDIT

The reason why the first parameter has to be an empty object is because of how extend works. Here is how jQuery defines extend:

jQuery.extend( target [, object1] [, objectN] )
   target    An object that will receive the new properties
             if additional objects are passed in or that will
             extend the jQuery namespace if it is the sole argument.
   object1   An object containing additional properties to merge in.
   objectN   Additional objects containing properties to merge in.

And additionally this phrase is important:

Keep in mind that the target object (first argument) will be modified, and will also be returned from $.extend().

So by passing the {} as first parameter, that empty object is extended and then returned.

Getting back to your example of settings = $.extend({}, defaults, options);. If you would change it to settings = $.extend(defaults, options);, the settings will be identical however here the defaults will also be changed. Thats why you need the first argument to be {}.

like image 101
miki725 Avatar answered Oct 21 '22 03:10

miki725