a simple question on jquery closure a simple question on jquery closure jquery jquery

a simple question on jquery closure


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:


CMS have given you the correct answer but I just want to add that this is not a closure. This is just the () operator being used to return the result of an expression which in this case is a function expression and the fact that in javascript, a returned anonymous function can be called directly. So this is simply combining both:

var x = (1+1); // <-- () evaluates an expression

and:

var arr = [0,1,2];arr.push(function(text){alert(text)});arr[3]('hello'); // <-- function returned by array called directly

And as for the $ parameter, that's just one of the characters that javascript allows for variable names. Your examples is exactly equivalent to:

(function(jQ){})(jQuery);(function(moo){})(mooTools);


The main point for doing this is so that objects created within the function's expression can be utilized from properties and methods attached to passed in objects, without exposing those objects publicly. This can aid in preventing variable collisions. It also allows for variables created to be accessed as private storage for anything that is attached..

(function($){//jQuery is available here as $
var myPrivateArray = []; //this is private
$.addItem = function(item) { myPrivateArray.push(item);}
})(jQuery);

//I can't access myPrivateArray here...//but I can use jQuery.addItem to add something.