Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are self-executing anonymous functions used in Javascript Module pattern?

In the module pattern in JavaScript "Immediately-Invoked Function Expressions" (also known as self-executing anonymous functions) are used as self executing functions that return an object. How can a self-executing function hide private variables and only expose the returned object. Why does this not happen with a normal JavaScript function? So in the following mini module, why could we not achieve the same concept of encapsulation without the enclosing ()()?

var Module = (function () {
    var privateVariable = "foo",
        privateMethod = function () {
            alert('private method');
        };

    return {
        PublicMethod: function () {
            alert(privateVariable); 
            privateMethod(); 
        }
    };
})();
like image 797
Brendan Avatar asked May 03 '13 22:05

Brendan


1 Answers

How can a self-executing function hide private variables and only expose the returned object. Why does this not happen with a normal JavaScript function?

It does happen with normal JavaScript functions.

function MakeModule() {
    var privateVariable = "foo",
        privateMethod = function () {
            alert('private method');
        };

    return {
        PublicMethod: function () {
            alert(privateVariable); 
            privateMethod(); 
        }
    };
}

var Module = MakeModule();

would work just fine.

The only difference is that the anonymous function introduces one less global variable and allows for itself to be garbage collected while MakeModule can't be collected unless explicitly deleted by the author.

like image 119
Mike Samuel Avatar answered Sep 24 '22 06:09

Mike Samuel