I started reading this: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
And they refer to anonymous closure:
This is the fundamental construct that makes it all possible, and
really is the single best feature of JavaScript. We’ll simply create
an anonymous function, and execute it immediately. All of the code
that runs inside the function lives in a closure, which provides
privacy and state throughout the lifetime of our application.
(function () {
// ... all vars and functions are in this scope only
// still maintains access to all globals
}());
- I don’t understand what happens in a self-executing anonymous
function closure-wise, that is different from a normal closure and
why is it so special? - What is the benefit in it?
Variables that are not defined within a closure get into the window variable and are global.
Example:
If you have this code, SOME_CONSTANT will be global to all files and code run within inline scripts etc, which may not be desired.
You can use the self-calling closure to keep the variable only inside this closure:
This way you can have modules that have variables global only to that module. For example, by having the code of each file enclosed in such an anonymous function.