Immediately-Invoked Function Expression ( IIFE )

It executes immediately after it’s created.

It has nothing to do with any event-handler for any events (such as document.onload).
The first pair of parentheses (function(){…}) turns the code within (in this case, a function) into an expression, and the second pair of parentheses (function(){…})() calls the function that results from that evaluated expression.

This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.
This is why, maybe, you confused this construction with an event-handler for window.onload, because it’s often used as this:


( function(){  
 // all your code here    
 var initializeApp = function() {};    
 window.onload = initializeApp ;    
 // ...
})();
// initializeApp is unreachable here (it’s undefined)

The function is executed right after it’s created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing the code doesn’t automatically mean that it’s executed. For example, if the IIFE is inside a function then it won’t be executed until the function is called.

Advertisements

Leave a Reply

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s