Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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(){}
like image 455
Mark Brown Avatar asked Jun 24 '11 13:06

Mark Brown


2 Answers

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

like image 82
zzzzBov Avatar answered Sep 30 '22 03:09

zzzzBov


$.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
like image 28
Alnitak Avatar answered Sep 30 '22 02:09

Alnitak