Hoppie
Hoppie

Reputation: 51

How to create jQuery functions?

I have seen a few different approaches to create jQuery(-namespaced) functions, but I cannot quite tell the actual difference between them.

jQuery.fn.myFunction = function() { ... };

jQuery.myFunction = function() { ... };

jQuery.fn.extend({ myFunction: function() { ... } });

Upvotes: 5

Views: 564

Answers (1)

David Hedlund
David Hedlund

Reputation: 129832

jQuery.fn.myFunction is what you use to create functions that will be available on every jQuery result set:

$('div').myFunction();

jQuery.myFunction is what you use to create helper functions that are just available on the jQuery object, such as $.inArray

Your last version extends the $.fn object with a new function, and is as such the functional equivalent of your first example.

Upvotes: 6

Related Questions