Reputation: 15706
One assigns a plugin to the jQuery prototype property. What's the point of doing this when one doesn't use 'new' with jQuery? There's only ever one instance of jQuery isn't there? So couldn't plugins be assigned directly to the singleton jQuery object?
Upvotes: 4
Views: 207
Reputation: 707786
Plugin methods must be automatically added to each new jQuery object that is created.
jQuery.fn
is the same as jQuery.prototype
so assigning a plugin method to jQuery.fn
is adding it to the jQuery prototype so whenever a new jQuery object is created, that method will automatically be available. Technically, it's a jQuery.fn.init
object, but the idea is the same.
Calling jQuery with a string like this:
$(".foo")
creates a new jQuery.fn.init object which gets its prototype from jQuery.fn (where plug-in methods are defined).
Here's the relevant jQuery code that shows a new object getting created:
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
Upvotes: 3