JavaScript · OOP · Programming

Understanding Self Executing Anonymous Functions

Anonymous function is one which has no reference name.

For example:

function (){};

Creating Self Executing Function

Now if we want to make it self-executing then use the following syntax:
1) Wrap the anonymous function within a round brackets.

( function() {...} )

2) Execute the function by adding the () in the end.

( function() {...} ) ();


What the code snippet basically does is that it creates a literal function and executes it immediately. Note that because the function gets executed, it forms a closure automatically. This helps in scoping and proper encapsulation.

We can add any functionality inside the anonymous function.

(
function() {
        var c = 'amit';
        var j = 'port';

        var fn = function() {return 'data '+c+' '+j;}
    }
)();

However, at this point the function just executes and returns and there is no way to call it again. This might not be very useful in most of the scenarios.

Referencing the Anonymous Function

To overcome this problem we need to pass the reference of the inner function back to the environment from where we can call it.

One way to do this can be the following:

(function() {
        var c = 'joe';
        var j = 'port';

        var fn = function() {return 'data '+c+' '+j;}

        window.fn = fn;// pass the reference to windows object
 })();

window.fn();// call the function

We are attaching the reference of the inner ‘fn’ function to the window object and now we can call it from anywhere else. This is the technique used in libraries like jQuery.

Using Parameters

Finally, we can also create such self-executing functions that can take parameters.
Parameters can be user defined data types or JavaScript host objects like ‘window’, ‘document’ etc.

var param = {"name":"joe","job":"pilot"};

(
function(p,w) {
        var c = p.name;
        var j = p.job;

        var fn = function() {return 'data '+c+' '+j;}

        w.fn = fn;

    }
)(param,window);

window.fn();

Notice how we have used the shorthand alias for window in our function. This helps code minification.

Summary

Self executing function is one of the most useful pattern.

  • Self executing function provide a very powerful and mechanism for encapsulation by providing automatic closure.
  • Helps create modular code.
  • Aids in code minification by allowing shorthand reference alias.
Advertisements

One thought on “Understanding Self Executing Anonymous Functions

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