Search code examples
iife

Can somebody explain this javascript fragment?


// JavaScript source code
var foo = (function () {
    var o = { bar: "bar" };

    return {
        bar: function () {
            console.log(o.bar);
        }
    };

})();

foo.bar();

What is going on? Is foo an object? Is it a named function? This looks like a hideous way to provide the class concept of private data members....


Solution

  • They are called IIFE's https://developer.mozilla.org/en-US/docs/Glossary/IIFE

    Check this example where IIFE's are used http://javascriptissexy.com/understand-javascript-closures-with-ease/

    Usually javascript modules are written in the pattern.

    var foo = function () {
        var o = { bar: "bar" };
    
        return {
            bar: function () {
                console.log(o.bar);
            }
        };
    
    };
    
    foo().bar();
    

    AND

    var foo = (function () {
        var o = { bar: "bar" };
    
        return {
            bar: function () {
                console.log(o.bar);
            }
        };
    
    })();
    
    foo.bar();
    

    are similar.