Mark Brown
Mark Brown

Reputation: 12524

What is the difference between $.pluginName and $.fn.pluginName

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(){}

Upvotes: 5

Views: 2116

Answers (2)

zzzzBov
zzzzBov

Reputation: 179066

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

Upvotes: 9

Alnitak
Alnitak

Reputation: 339816

$.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

Upvotes: 2

Related Questions