Javascript IIFE anonymous function [duplicate]

假如想象 提交于 2019-12-25 16:08:32

问题


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


来源:https://stackoverflow.com/questions/27582698/javascript-iife-anonymous-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!