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');

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');

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

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:


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


Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s