Possible Duplicate:
Is there a difference between (function() {…}()); and (function() {…})();?
I’ve seen the following syntax used to prevent variables from getting into global scope:
(function ($, undefined)
{
})(jQuery);
More recently I’ve seen code doing it this way:
(function ($, undefined)
{
} (jQuery));
I find the 1st way makes the most sense to me. I mentally read it as:
I’ve defined a function and I wish to wrap it into an expression, (the first set of parenthesis). That expression is a function object which I then wish to call using method syntax and the parameter I’m passing to this function object is jQuery.
The 2nd syntax is less clear to me, because it looks like the outer parenthesis are unnecessary.
My javascript knowledge isn’t quite good enough yet to feel comfortable w/ the 2nd syntax.
Do these produce identical behavior? Is there any difference at all?
What would happen if you did this?
function ($, undefined)
{
} (jQuery);
If a
functionkeyword occurs at the start of a line it is parsed as a functionstatementdeclaration. Funcsion statements require a function name so the 3rd option you present is not allowed (you can test that yourself).If the
functionkeyword appears elsewhere it is parsed as a function expression and is allowed to be anonymous. There are many ways to do this but the convention for the module pattern you shown is wraping the construct in parenthesis. (Some byte-savers like using a unary operator like + or ~ instead)If you choose to use the parenthesis puting the last one inside (1st version) or outside (2nd version) is a matter of personal preference. I prefer the 2nd one since the parenthesis wraps the whole pattern instead of just the function.