0

I've been trying to understand exactly how IIFEs work in regards to anonymous functions. I understand their use in avoiding global variable collisions and that they create their own local scope.

I'm not clear on what happens when an anonymous function like this is called.

(function () {
  var myVar = 'foo';
  }
)()

If this is immediately invoked and it is not available in the global scope, where is it available? How would I access myVar?

byrdr
  • 5,197
  • 12
  • 48
  • 78
  • 2
    you cannot access to myVar, IIFE work as a well protected singleton – ale Dec 20 '14 at 17:43
  • You won't access it unless you make it a property of `window` or something else in the scope above. – Alexander O'Mara Dec 20 '14 at 17:43
  • Would that mean passing in (window) to the invoking parenthesis? – byrdr Dec 20 '14 at 17:44
  • @byrdr No, but you could, it will help minification. You would need to do `window.myVar` in either case. – Alexander O'Mara Dec 20 '14 at 17:46
  • OK, that makes sense. So unless I explicitly define access to something like "window" they will not be accessible on their own. – byrdr Dec 20 '14 at 17:48
  • 2
    Yes - that, in fact is one of the reasons you'd write code like that: to protect the global namespace from pollution, so that your script won't step on variables used by other scripts, and vice-versa. – Pointy Dec 20 '14 at 17:52

1 Answers1

0

This notation is known as module pattern

var myModule = function () {
      var privateVar = "foo";
      function privateMethod() {
       return "bar";

      }

      return {
        publicMethod : function(){
          return 'foo';
        }
      }
}

To make this module completely isolated from the global scope, we can close it in a IIFE

(function (setUp) {
      var privateVar = setUp;
      function privateMethod() {
       return "bar";

      }

      return {
        publicMethod : function(){
          return 'foo';
        }
      }
})(window.setUp);
ale
  • 10,012
  • 5
  • 40
  • 49