This post explains self-executing functions and its benefits. So lets started by breaking down a normal function and converting it into one …
var myVar = "This is a normal function...";
function ShowAlert(textToAlert)
{
alert(textToAlert);
}
ShowAlert(myVar);
We all know that functions are also objects in JavaScript. Thus they can be evaluated using the eval() function and also in the case of setInterval() function you can pass the name of the function as an object. Thus like other objects, we can also use grouping operators like ( and ).
var myVar = "This is still a normal function...";
function ShowAlert(textToAlert)
{
alert(textToAlert);
}
(ShowAlert)(myVar);
We are halfway there. Lets replace the name of the function with the function definition and make it a single statement.
var myVar = "This is a self-executing function...";
(function ShowAlert(textToAlert)
{
alert(textToAlert);
})(myVar);
Ok. So far so good. Since we are going to run this function as soon as we create it, it doesn’t need a name. Next step is to make this function an anonymous function.
var myVar = "This is an anonymous self-executing function...";
(function (textToAlert)
{
alert(textToAlert);
})(myVar);
And voila… We have created a self-executing anonymous function.
Although in this example, the advantage might not be obvious, but in real-world, this technique is quite helpful as it encapsulates the functionality and also prevents the cluttering of the global namespace. If you take a peek at the jQuery source code, you will notice that the whole library is wrapped in a single, self-executing function that is assigned to the jQuery global object. It’s precisely the reason that jQuery doesn’t pollute the global namespace nearly as much as other libraries.
« Open Chrome in Incognito mode Office 2010 : Free PDF Book »


