Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this JavaScript/jQuery syntax mean?

What does the following syntax mean?

(function($){
    $.fn.columnize = function(options) {
    ...

What’s function($)?

What’s $.fn. …?

like image 452
aneuryzm Avatar asked Feb 22 '10 08:02

aneuryzm


2 Answers

This convention is used when writing plugins to ensure there is no confilict with other Javascript libraries using the $ notation, whilst ensuring the plugin author can still use this notataion:

(function($){
    ...
})(jQuery); 

The author is declaring an anonymous function with a single parameter ($), then immediately calling it and passing the jQuery object to it. This ensures the function is called and that everything in it is defined.

A longer notation might be:

function MyDefs($){
    ...
}
MyDefs(jQuery);

Although that would create a variable MyDefs in the global namespace. The anonymous function pattern leaves the global namespace empty, avoiding conflicts.

like image 179
James Wiseman Avatar answered Sep 21 '22 10:09

James Wiseman


It declares the columnize function as a jQuery plugin allowing you to use it on elements like this $('.someSelector').columnize(). You could read more about plugin authoring here.

like image 26
Darin Dimitrov Avatar answered Sep 18 '22 10:09

Darin Dimitrov