Javascript IIFE anonymous function [duplicate]

2019-09-06 21:08发布

问题:

This question already has an answer here:

  • What is the (function() { } )() construct in JavaScript? 23 answers

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?

回答1:

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);