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

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

在这:

//Bunch of code...

当前回答

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

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

其他回答

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

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

这都是关于变量作用域的。默认情况下,在自执行函数中声明的变量仅可用于自执行函数中的代码。这允许编写代码时不考虑变量在其他JavaScript代码块中的命名方式。

例如,正如Alexander在评论中提到的:

(函数(){ Var foo = 3; console.log (foo); }) (); console.log (foo);

这将首先记录3,然后在下一个console.log上抛出一个错误,因为foo没有定义。

由于Javascript中的函数是一等对象,通过这样定义它,它有效地定义了一个类似于c++或c#的“类”。

该函数可以定义局部变量,并在其中包含函数。内部函数(实际上是实例方法)可以访问局部变量(实际上是实例变量),但它们将与脚本的其余部分隔离。

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

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…