JavaScript Patterns: Self-invocation

Self-invocation (also known as auto-invocation) is when a function executes immediately upon it's definition. 

This is a core pattern and serves as the foundation for many other patterns of JavaScript development.  A self-invoking function is a standard function, just with a set of parentheses appended to the end.

   
function(){
	var msg = "hello";
	alert(msg);
}();

The above example defines an anonymous function. This creates a literal function, yet since no name is attributed to it, the value is never stored. The trailing parenthesis tell the function to execute, just as if you were calling a named function. Once the function terminates, the variables are discarded and the global object remains unchanged. It it recommended that an extra set of parentheses wrap the function definition as well so to provide a visual clue to the developer that the function isn’t a normal function.

   
(function(){
	var msg = "hello";
	alert(msg);
})();

In the event where a self-invoking function requires parameters, they can be passed in the same manor that you would a regular function

   
(function(id){
	var msg = "hello";
	alert(msg);
})('idvalue');

In an effort to protect the global object, all JavaScript applications should be written within a self-invoking function. This will create an application scope in which variables can be created without the fear of them colliding with other applications. If a global variable is needed, developers must take the extra step by setting them directly within the window object. For example window.foo = ‘bar’;. Self-invocation is a fundamental pattern of professional JavaScript development.

Author

Admin

comments powered by Disqus

Categories

Recent Tweets

@jeffrey_doucet @Brian_Bancroft Canadians, self define themselves as NOT American, rather than being Proud Canadians
Retweeted by @dyardy Why do so many Canadians obsess over American policy that won’t impact us while being fairly ambivalent to day-to-d… twitter.com/i/web/status/9…
@melrobbins I was looking for 50$ earlier today, and still can't find it...ideas :)
Trump Watches Up To 8 Hours Of TV Per Day | HuffPost #SmartNews ===that explains everything huffingtonpost.com/entry/trump-te…
Retweeted by @dyardy Boston https://t.co/QmtMIF8P0F