In javascript, when would you want to use this:
(function(){
//Bunch of code...
})();
over this:
//Bunch of code...
In javascript, when would you want to use this:
(function(){
//Bunch of code...
})();
over this:
//Bunch of code...
Its all about variable scoping. Variables declared in the self executing function are, by default, only available to code within the self executing function. This allows code to be written without concern of how variables are named in other blocks of javascript code.
Since functions in Javascript are first-class object, by defining it that way, it effectively defines a "class" much like C++ or C#.
That function can define local variables, and have functions within it. The internal functions (effectively instance methods) will have access to the local variables (effectively instance variables), but they will be isolated from the rest of the script.
Scope isolation, maybe. So that the variables inside the function declaration don't pollute the outer namespace.
Of course, on half the JS implementations out there, they will anyway.
One difference is that the variables that you declare in the function are local, so they goes away when you exit the function and the don't conflict with other variables in other code.
Is there a parameter and the "Bunch of code" returns a function?
var a = function(x) { return function() { document.write(x); } }(something);
Closure. The value of something
gets used by the function assigned to a
. something
could have some varying value (for loop) and every time a has a new function.
Self-invocation (also known as auto-invocation) is when a function executes immediately upon its definition. This is a core pattern and serves as the foundation for many other patterns of JavaScript development.
I am a great fan :) of it because:
* It keeps code to a minimum
* It enforces separation of behavior from presentation
* It provides a closure which prevents naming conflicts
Enormously – (Why you should say its good?)
* It’s about defining and executing a function all at once.
* You could have that self-executing function return a value and pass the function as a param to another function.
* It’s good for encapsulation.
* It’s also good for block scoping.
* Yeah, you can enclose all your .js files in a self-executing function and can prevent global namespace pollution. ;)
More here: