在javascript中,什么时候你想使用这个:

(function(){
    //Bunch of code...
})();

在这:

//Bunch of code...

当前回答

下面是一个实例,说明了自我调用匿名函数的用处。

for( var i = 0; i < 10; i++ ) {
  setTimeout(function(){
    console.log(i)
  })
}

输出:10,10,10,10…

for( var i = 0; i < 10; i++ ) {
  (function(num){
    setTimeout(function(){
      console.log(num)
    })
  })(i)
}

输出:0,1,2,3,4…

其他回答

给你一个简单的问题:“在javascript中,什么时候你想使用这个:…”

我喜欢@ken_browning和@sean_holding的回答,但这里有另一个用例,我没有看到提到:

let red_tree = new Node(10);

(async function () {
    for (let i = 0; i < 1000; i++) {
        await red_tree.insert(i);
    }
})();

console.log('----->red_tree.printInOrder():', red_tree.printInOrder());

在节点。插入是某种异步操作。

我不能只是调用等待没有异步关键字在我的函数的声明,我不需要一个命名函数以后使用,但需要等待插入调用或我需要一些其他更丰富的功能(谁知道?)。

自执行函数用于管理变量的作用域。

变量的作用域是程序中定义变量的区域。

全局变量具有全局作用域;它在JavaScript代码中的任何地方都有定义,并且可以从脚本中的任何地方访问,甚至在函数中。另一方面,在函数中声明的变量只能在函数体中定义。 它们是局部变量,具有局部作用域,并且只能在该函数中访问。函数参数也算作局部变量,只在函数体中定义。

如下所示,您可以在函数中访问全局变量变量,并注意在函数体中,具有相同名称的局部变量优先于全局变量。

var globalvar = "globalvar"; // this var can be accessed anywhere within the script

function scope() {
    alert(globalvar);
    var localvar = "localvar"; //can only be accessed within the function scope
}

scope(); 

因此,基本上,自执行函数允许编写代码,而无需考虑其他javascript代码块中的变量如何命名。

命名空间。JavaScript的作用域是函数级的。

IIRC允许你创建私有属性和方法。

你可以使用这个函数返回值:

var Test = (function (){ const alternative = function(){ return 'Error Get Function '}, methods = { GetName: alternative, GetAge:alternative } // If the condition is not met, the default text will be returned // replace to 55 < 44 if( 55 > 44){ // Function one methods.GetName = function (name) { return name; }; // Function Two methods.GetAge = function (age) { return age; }; } return methods; }()); // Call console.log( Test.GetName("Yehia") ); console.log( Test.GetAge(66) );