tags:

views:

29

answers:

1

I'm looking at the Plugin Authoring article at http://docs.jquery.com/Plugins/Authoring and saw this example in the Defaults and Options section:

$.fn.tooltip = function( options ) {  
var settings = {
  'location'         : 'top',
  'background-color' : 'blue'
};
return this.each(function() {        
  // If options exist, lets merge them
  // with our default settings
  if ( options ) { 
    $.extend( settings, options );
  }

I don't fully understand why the .extend call is inside the this.each block? My first intuition would be to write it as:

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

return this.each(function() { 

So I moved the .extend call above the return (and replaced the ugly if with a || {} - I assume that makes sense?).

Is there anything I'm not seeing here? Any weird closure related stuff maybe? As in: Modifying the settings globally vs. only on that call? (Edit: Apparently I am not - http://jsfiddle.net/fVSDH/ )

+3  A: 

You're right.

It does not make any sense extending the settings object for each element in the jQuery collection.

Also your || {} is pretty standard, battleproved and good.

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

Is another optimization that can be made here.

jAndy