a simple question on jquery closure

yretuta picture yretuta · Jan 8, 2010 · Viewed 7.9k times · Source

what does this mean?

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

to make the question clearer, what does wrapping a function in parenthesis mean in JS (sorry, I'm a bit confused on the concept of closures). What about the $ parameter? and the "jQuery" in the end parenthesis?

Can I do the same with mootools and combine them in 1 JS file?

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

(function($){})(mooTools);

I have only worked with jquery and am planning to work with Mootools

Answer

Christian C. Salvadó picture Christian C. Salvadó · Jan 8, 2010

Wrapping a function between parenthesis ensures this function to be evaluated as a function expression.

That happens because the Grouping Operator (the parentheses), can only evaluate expressions.

If no parenthesis are used, it will be interpreted as a function declaration, and it will cause a syntax error, since the function name is not optional for function declarations.

(function(arg){
  alert(arg); // alerts test
})("test");

In the above example, the function expression is automatically executed, passing an argument.

That pattern is heavily used by jQuery plugins, since jQuery can run in noConflict mode, the $ global variable will not be created, so the jQuery global object is passed as an argument of this anonymous function and inside of that function, you can freely refer to it as $ (the received argument).

Keep in mind that also, the function context (the this keyword) inside self-executing function expressions invoked like the above example, will refer always to the Global object.

For a more in-depth info about the differences between function expressions and function declarations, give a look to the following resources: