什么是自执行匿名函数或者这段代码在做什么?

sat*_*mon 6 javascript function self-executing-function

var module = {};


(function(exports){

  exports.notGlobalFunction = function() {
    console.log('I am not global');
  };  

}(module));

function notGlobalFunction() {
  console.log('I am global');
}

notGlobalFunction(); //outputs "I am global"
module.notGlobalFunction(); //outputs "I am not global"
Run Code Online (Sandbox Code Playgroud)

谁能帮我理解这里发生了什么?如果你打电话notGlobalFunction(),我会得到它,它只会调用第二个函数.

但是在var module = {}做什么?为什么在第一个函数内再次调用?

它说这通常被称为自动执行的匿名函数,但我不知道这意味着什么.

jfr*_*d00 25

立即调用的函数通常用于创建私有的本地函数作用域,不能从外部访问,并且可以定义它自己的本地符号而不影响外部世界.这通常是一种很好的做法,但在这种特殊情况下,除了几行代码之外,我没有看到它产生任何好处,因为它不用于任何东西.

这段代码:

(function(exports){

  exports.notGlobalFunction = function() {
    console.log('I am not global');
  };  

}(module));
Run Code Online (Sandbox Code Playgroud)

如果没有像这样的立即调用,则与一段代码完全相同:

module.notGlobalFunction = function() {
   console.log('I am not global');
};  
Run Code Online (Sandbox Code Playgroud)

不同的一点是,在第一个中,创建了一个别名,用于modules调用exports,它是立即调用的功能块的本地.但是,别名没有什么独特之处,代码也可以modules直接使用.


该变量modules被创建为单个全局父对象,然后可以将许多其他全局变量保存为属性.这通常称为"命名空间".这通常是一个很好的设计模式,因为它最大限度地减少了可能与同一项目/页面中使用的其他代码段冲突的顶级全局变量的数量.

所以,而不是像这样制作多个顶级变量:

var x, y, z;
Run Code Online (Sandbox Code Playgroud)

可以像这样制作一个顶级变量:

var modules = {};
Run Code Online (Sandbox Code Playgroud)

然后,将所有其他全局变量作为属性附加到它:

modules.x = 5;
modules.y = 10;
modules.z = 0;
Run Code Online (Sandbox Code Playgroud)

这样,虽然仍有多个全局变量,但只有一个顶级全局变量可能与其他代码冲突.


类似地,立即调用的函数创建一个本地私有作用域,其中可以创建对该作用域本地的变量,并且不会干扰其他代码段:

(function() {
    var x, y, z;

    // variables x, y and z are available to any code inside this immediately invoked function
    // and they act like global variables inside this function block and
    // there values will persist for the lifetime of the program
    // But, they are not truly global and will not interfere with any other global
    // variables and cannot be accessed by code outside this block.
    // They create both privacy and isolation, yet work just as well


})();
Run Code Online (Sandbox Code Playgroud)

将参数传递给立即调用的函数只是将值传递给立即调用的函数的范围,该范围将具有它自己的本地符号:

(function(exports) {
    // creates a local symbol in this function block called exports
    // that is assigned an initial value of module
})(module);
Run Code Online (Sandbox Code Playgroud)