Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery function declaration

Tags:

jquery

What is the difference between $.myfunc and $.fn.myfunc? I can see one needs return value and use $().myfunc() to invoke while the other one is not. Can the community suggest me some reference or keywords to get more understanding? Thanks.

like image 409
Stan Avatar asked Dec 22 '22 12:12

Stan


2 Answers

$.myfunc refers to a "static" or global function in the jquery namespace. It is not reliant on jquery initialisation via a selector such as $('#id').myfunc(...).

$.ajax is an example.

$.fn.myfunc on the other hand adds myfunc to the prototype of the jquery object, so that when a jquery objetc is created via a selector $('#id') the new object has a method called myfunc that is invokable in the context of the newly created jquery object.

like image 167
Xhalent Avatar answered Dec 29 '22 00:12

Xhalent


$.fn is a shortcut to jQuery.prototype. It augments the jQuery object. It is used when working with a set of elements chosen with a selector.

$('a').newWindow();

I believe assigning a property directly to $ will make it a utility function, such as each() (not tied to a particular set of matched elements).

var sum = $.arraySum(array);
like image 29
alex Avatar answered Dec 28 '22 22:12

alex