5

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(){}
Nissa
  • 4,636
  • 8
  • 29
  • 37
Mark Brown
  • 12,026
  • 8
  • 27
  • 32
  • asked lots of times.....possible duplicate of [jQuery Plugin Authoring: Why do some do jQuery.pluginName and others jQuery.fn.pluginName?](http://stackoverflow.com/questions/538043/jquery-plugin-authoring-why-do-some-do-jquery-pluginname-and-others-jquery-fn-pl) – redsquare Jun 24 '11 at 14:06
  • @redsquare. Thanks for the link. I looked, but I couldn't find any similar questions. – Mark Brown Jun 24 '11 at 15:23
  • This is basically asking the difference between `$` and `$.fn`. – Nissa Feb 13 '17 at 01:57
  • Possible duplicate of [jQuery Plugin Authoring: Why do some do jQuery.pluginName and others jQuery.fn.pluginName?](https://stackoverflow.com/questions/538043/jquery-plugin-authoring-why-do-some-do-jquery-pluginname-and-others-jquery-fn-p) – Dzyann Jan 11 '18 at 12:47

2 Answers2

9

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

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
2

$.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
Alnitak
  • 334,560
  • 70
  • 407
  • 495