Standalone Parentheses In Javascript
Solution 1:
This code creates a function expression, then calls it immediately.
It's the same as
var unnamed = function() { ... };
(unnamed) ();
Solution 2:
The last two parantheses before the ;
execute the anonymous function directly. The other two parantheses are optional and just some sort of convention.
This pattern is commonly used for not polluting the global namespace:
(function() {
var a = 42;
})();
alert(a); // a is undefined
Paul Irish has a pretty good screencast about this and other javascript patterns: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/
Solution 3:
This is the basis for what is called the Module pattern in Javascript. See these articles for more information:
http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
http://yuiblog.com/blog/2007/06/12/module-pattern/
Essentially, as the articles state, this pattern is perfect for maintaining privacy and state, but also allow loose coupling and chaining of your Javascript modules.
Solution 4:
The standalone parentheses ()
means to execute the function, in this code, it's a anonymous function.
Solution 5:
Creates annonymous function and calls it, therefore avoiding pollution of the namespace and memory for functions that are called only once.
Although similar to:
var f = function () { ... };
f();
This variant avoids creating a variable f, which saves memory and avoids namespace conflicts.
Post a Comment for "Standalone Parentheses In Javascript"