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?
Possible reasons (for the second example)…
Inherited ignorance… (saw it done that way, and copied the practice)
Intrinsic ignorance… (saw it done properly as in your last code block, but replaced the cached object with an on-the-fly object and didn’t know that the empty object should be removed)
Global warming.
Lack of attention to detail… (similar to point 2, knows it isn’t necessary but never really took the time to examine the code)
Global cooling.
Overly defensive coding… (afraid that the defaults may someday be reworked into a reusable object, and is afraid that the empty object won’t be inserted at that time)
jQuery developers always do what the voices tell them 😉
Overall, you’re right. The middle object is created, copied to an empty object, then discarded. It’s an unnecessary and wasteful practice.