Self-Invoking Functions
A self-invoking (also called self-executing) function is a nameless (anonymous) function that is invoked immediately after its definition.
An anonymous function is enclosed inside a set of parentheses followed
by another set of parentheses (), which
does the execution
(function(){
console.log(Math.PI);
})();
Self-invoking functions are useful for initialization tasks and for one-time code executions, without the need of creating global variables.
Parameters can also be passed to self-invoking functions as shown in the example below.
(function(x){
console.log(x);
})("Hello, World!");
A self-invoking function can have variables and methods but they
cannot be accessed from outside of it. To access them, the global
window object has to be passed as a
parameter.
Consider a self-invoking function below, containing the variable
pi and the function
e(). A global
window object is passed and both
pi and e() are
assigned to the global variables
window.pi and
window.e respectively
(function(){
var pi = 3.141;
function e() {
return Math.E;
}
window.pi = pi;
window.e = e;
})(window);
In the browser console, the command
pi will return
3.141 and the command
e() will return
2.718281828459045.
> pi; // 3.141
> e(); // 2.718281828459045