Self executing functions in JavaScript


JavaScript has bunch of cool features; one of them can be self executing functions. :)

Also this self invocation feature could be surrounded by the best practices for JavaScript.

Let’s have an example of an anonymous self invoking function:

 (function(){
 var test =  2;
 alert(test);
 })();
 

Here, test variable has its own local scope, means it doesn’t interface with or pollute global scope and it dies out(remains as long as there’s somewhere in the page or in an event that references the variable you declared in your closure: Thanks Dan Beam for this correction :) ) when the function terminates.

One simple example:

 var testVar = "Hi there";

(function testFunction(str)
{
alert(str);
})( testVar );

One more scoping example(by Dan Beam):

var class = (function () {
var private = function () { alert("Hey, I'm still here!"); };
return ({ test: function () { private(); }});
})();

// more JavaScript

class.test();

Self-invocation (also known as auto-invocation) is when a function executes immediately upon its definition. This is a core pattern and serves as the foundation for many other patterns of JavaScript development.

I am a great fan :) of it because:

  • It keeps code to a minimum
  • It enforces separation of behavior from presentation
  • It provides a closure which prevents naming conflicts

Enormously – (Why you should say its good?)

  • It’s about defining and executing a function all at once.
  • You could have that self-executing function return a value and pass the function as a param to another function.
  • It’s also good for block scoping.
  • Yeah, you can enclose all your .js files in a self-executing function and can prevent global namespace pollution. ;)

jQuery pursue such struct.

 (function($) {
 // $() is available here
 })(jQuery);
 

It’s precisely the reason that jQuery doesn’t pollute the global namespace nearly as much as other libraries.

Cheers!

:D

About these ads

6 thoughts on “Self executing functions in JavaScript

  1. “and of-course it dies out when the function terminates”

    This is wrong. As long as there’s somewhere in the page or in an event that references the variable you declared in your closure (and there often is), it will remain in memory (just not publicly accessible) until there is no further “next use” (which is when it garbage collected).

    var class = (function () {
    var private = function () { alert(“Hey, I’m still here!”); };
    return ({ test: function () { private(); }});
    })();

    // more JavaScript

    class.test();

    This is one of the reasons self-executing functions are so cool – they introduce a public / private scope and keep your private variables in memory (though this can also lead to higher memory reuse if you have multiple closures doing alot of the same stuff).

  2. This is a bit tardy, but to (hopefully) clear things up a bit:

    the closure in Dan Beam’s example is the function assigned to “test” in the returned object. Inasmuch as that function is made available outside of the function in which it was defined (and may be executed after the outer function has terminated; and can reference the variables, parameters, and such from the outer function), it becomes a closure.

    The preceding example, while illustrating self-executing function behavior, is not a closure.

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 )

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