Encapsulated anonymous functions in JavaScript

In several place we see some syntax like (function(){})(). What actually it means?

Well will see some very basic example of function writing pattern, with which we are more familiar.

For example, one creates a named function like this:

function finc1(){
alert('normal func');
}
finc1();

but we can write the same function in different way, like we create an anonymous function and assign it to a variable:

var finc1 = function(){
alert('anonym func assigned in a var');
};
finc1();

So, now if we think in different way as follows:

(function(){
alert('anonym func executing immediately');
})();

Here, it encapsulates a block of code by creating an anonymous function, then wrapping it in brackets and executing it immediately.
So what did we get from here? The function are created and called immediately, we just removed one step according to previous one. So, we can assume that the previous function and this function are same. But still there is a difference, that is we have encapsulated it with braces. So the vars and function declared inside of this encapsulated area will not be accessible from outside. But there also have some way that we can inject an object in to it. Which can carryout the encapsulated functions within the object we injected if we want, The following code are sample for that:

(function(j){
alert(j);
})(k);

Here encapsulated function have a parameter j and it passes k immediately where k is expected defined previously.

Advertisements