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

其他回答

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

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的作用域是函数级的。

我不敢相信没有一个答案提到隐含的全局变量。

(function(){})()构造不能防止隐含的全局变量,这对我来说是更大的问题,参见http://yuiblog.com/blog/2006/06/01/global-domination/

基本上,函数块确保你定义的所有依赖的“全局变量”都限制在你的程序中,它不保护你不定义隐式全局变量。JSHint或类似的文件可以提供关于如何防御这种行为的建议。

更简洁的var App ={}语法提供了类似级别的保护,并且可以在“公共”页面上包装在函数块中。(请参阅Ember.js或SproutCore了解使用此结构的库的真实示例)

至于私有属性,除非您正在创建一个公共框架或库,否则它们有点被高估了,但如果您需要实现它们,Douglas Crockford有一些很好的想法。

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

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中的函数是一等对象,通过这样定义它,它有效地定义了一个类似于c++或c#的“类”。

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