in jQuery what is the difference between $.myFunction and $.fn.myFunction?
I'm delving into writing plugins for jQuery and I'm trying to understand the distinction between $.f and $.fn.f
I've seen pluggin authors 开发者_StackOverflow社区use both, or sometimes assign $.f = $.fn.f
Can someone explain this to me, reasoning, benefits, etc?
Looking at the jQuery source code will clear things up. By the way, jQuery
and $
refer to the same object, and this is how the jQuery object is defined:
var jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context );
}
jQuery
is a function and in Javascript, a function is also an object of the type Function
. So jQuery.f
or $.f
attaches f
to the jQuery Function
object, or call it the jQuery class if you will.
if you look at jQuery's source, you'll see that jQuery.prototype
has been assigned to jQuery.fn
jQuery.fn = jQuery.prototype
So, whenever you attach a method (or property) to jQuery.fn
, as in jQuery.fn.f = ..
, or $.fn.f = ..
, or jQuery.prototype.f = ..
, or $.prototype.f = ..
, that method will be available to all instances of this jQuery class (again, there are no classes in Javascript, but it may help in understanding).
Whenever you invoke the jQuery()
function, as in jQuery("#someID")
, a new jQuery instance is created on this line:
return new jQuery.fn.init( selector, context );
and this instance has all the methods we attached to the prototype, but not the methods that were attached directly to the Function
object.
You will get an exception if you try calling a function that wasn't defined at the right place.
$.doNothing = function() {
// oh noez, i do nuttin
}
// does exactly as advertised, nothing
$.doNothing();
var jQueryEnhancedObjectOnSteroids = $("body");
// Uncaught TypeError: Object #<an Object> has no method 'doNothing'
jQueryEnhancedObjectOnSteroids.doNothing();
Oh, and finally to cut a long thread short and to answer your question - doing $.f = $.fn.f
allows you to use the function as a plugin or a utility method (in jquery lingo).
The $.f
is a utility function whereas $.fn.f
is a jQuery plugin / method.
A utility function is basically a function within the jQuery namespace that is useful for performing some operation, for example, $.isArray(obj)
checks if an object obj
is an array. It is useful to put functions in the jQuery namespace if you'll use them often and also to avoid global namespace pollution.
jQuery methods on the other hand operate on jQuery objects/wrapped sets. For example, $(document.body).append('<p>Hello</p>');
will append a paragraph containing Hello to the body element of the document. $.fn
is a shorthand for $.prototype
in later versions of jQuery (it wasn't always in earlier versions of the library). You would use this when writing your own plugins.
The $.fn.f
is simply a shortcut to jQuery.prototype
By using the fn
, you can add plugin methods without using the extend method:
jQuery.fn.myPlugin = function(opts) { ... }
精彩评论