I see the following two patterns quite often. What is the difference between the two? When is each appropriate?
$.pluginName = function(){}
and
$.fn.pluginName = function(){}
Very simple:
$.fn.pluginName
is a function callable on all jQuery.init
* objects. This is useful for making chain-able functions to use with objects:
Example:
$.fn.foo = function(){...};
$('#bar').foo();
To continue chaining objects, you need to return another jQuery.init
object (could be the original one, or a filtered one):
$.fn.foo = function(){ return this; };
$.pluginName
is a function callable as $.pluginName()
. This is useful for making utility functions, or storing a particular plugin's default states.
Example:
$.foo = function(){...};
bar = $.foo();
*The jQuery factory function (jQuery()
or $()
) actually returns a new jQuery.init
object
$.pluginName
is for utility functions that have been added to the jQuery namespace, such as:
$.isArray();
$.extend();
etc
$.fn.pluginName
is for functions that work on lists of elements as returned by the jQuery $(...)
function:
$(...).attr( ... );
$(...).first( ... );
etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With