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

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

在这:

//Bunch of code...

当前回答

此方法用于闭包。有关闭包的更多信息,请阅读此链接。

其他回答

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

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

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

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

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代码块中的变量如何命名。

此方法用于闭包。有关闭包的更多信息,请阅读此链接。

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

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