2

// 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....

SirPaulMuaddib
  • 233
  • 2
  • 9
  • 2
    Possible duplicate of [What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?](https://stackoverflow.com/questions/2421911/what-is-the-purpose-of-wrapping-whole-javascript-files-in-anonymous-functions-li) – SLaks Nov 14 '17 at 22:23
  • @SLaks I would say no. That question is about entire files, where the anonymous function purely runs code and does not return a value. – McKayla Nov 14 '17 at 22:30

2 Answers2

1

foo is an object. It is the object following the return statement.

This code is declaring a function within those parentheses and then immediately calling it. foo is then assigned whatever value that function returns.

McKayla
  • 6,879
  • 5
  • 36
  • 48
1

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.

Nandu Kalidindi
  • 6,075
  • 1
  • 23
  • 36
  • Yes, when you add those extra brackets, you are executing the function then and there during assignment. It's like you have the return value already. Check through the article linked above, it has a nice example. – Nandu Kalidindi Nov 14 '17 at 22:41