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

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

在这:

//Bunch of code...

当前回答

自调用函数在javascript:

自动调用(启动)自调用表达式,而不需要调用。自调用表达式在创建后立即被调用。这主要用于避免命名冲突以及实现封装。变量或声明的对象在此函数之外不可访问。为了避免最小化(filename.min)的问题,总是使用自执行函数。

其他回答

给你一个简单的问题:“在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());

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

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

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

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…

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

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

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

可能是范围隔离。这样函数声明中的变量就不会污染外部命名空间。

当然,在一半的JS实现中,它们都是如此。