Both ways are almost identical. However, some small differences exist, in the following aspects -
- Speed
- Code style
- Naming your plugin elsewhere
Speed :
Negligible. You may ignore this aspect since it is unlikely you will notice performance differences between the two.
Code style :
the extend version adheres to the Object literal code style, which may seem a bit more elegant for some. For instance, if your plug-in uses the Object literal abundantly, you might prefer wrapping it using $.extend({}).
Naming your plugin elsewhere :
There is one other (significant, in my opinion) advantage in using the $.fn.a style - you can store your plugin's name elsewhere, anywhere in your code, then use its reference when adding the plugin to jQuery's namespace. This cannot be done when extending using an object literal. This advantage is somewhat relative to the length of your code, and to the number of occurrences of the plugin's name. One also might argue that the average coder rarely changes the name of his plugin, and if he does, it won't take long in most cases.
Example :
;(function($) {
// Declare your plugin's name here
var PLUGIN_NS = 'myPluginName';
// ... some arbitrary code here ...
// The jQuery plugin hook
$.fn[ PLUGIN_NS ] = function( args ) {
if ( $.type(args) !== 'object' )
var args = {};
var options = $.extend({}, $.fn[ PLUGIN_NS ].defaults, args);
// iterate over each matching element
return this.each({
var obj = $(this);
// we can still use PLUGIN_NS inside the plugin
obj.data( PLUGIN_NS+'Data' , args );
// ... rest of plugin code ...
});
};
// ----------------
// PRIVATE defaults
// ----------------
var defaults = {
foo: 1,
bar: "bar"
};
// ------------------------------------------------------------
// PUBLIC defaults
// returns a copy of private defaults.
// public methods cannot change the private defaults var.
// ------------------------------------------------------------
// we can use PLUGIN_NS outside the plugin too.
$.fn[ PLUGIN_NS ].defaults = function() {
return $.extend({}, defaults);
};
})(jQuery);
Now we can call the plugin, and defaults, like so:
$("div#myDiv").myPluginName({foo:2});
var originalFoo = $("div#myDiv").myPluginName.defaults().foo;
To change the plugin's name, change the PLUGIN_NS var.
This may be preferable over changing each occurrence of myPluginName inside the plugin code.