Why use jQuery.fn to add a plugin?
So I'm under the impression that jQuery.fn is a shortcut for jQuery.prototype. But isn't a plugin a method of the jQuery object? Why would I want to add a method to the prototype? Wouldn't adding a method to the pro开发者_如何学编程totype give the method to objects made using the jQuery object as a constructor (as opposed to adding the method to the jQuery object itself)?
It is even a bit more complicated (or at least it seems so). Have a look at the source code (jQuery 1.6.2):
When you call jQuery(selector)
you are actually calling
return new jQuery.fn.init( selector, context, rootjQuery );
In addition we have jQuery.fn.init.prototype = jQuery.fn
.
So by extending jQuery.fn
, we also extend jQuery.fn.init.prototype
.
As every object we create with new jQuery.fn.init
(by calling jQuery()
) has a reference to the prototype, every object created in the past or in the future will have access to every method we assign to jQuery.fn
.
I hope this clears up your confusion. If not, just ask :)
jQuery has a documentation about this at Plugins/Authoring.
There are two different methods of adding a new plugin to the jQuery plugin:
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
The (function($))
is more safer than using the below one since an overwrite using something else except the $
may cause the plugin to not work.
jQuery.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
精彩评论