在javascript中,什么时候你想使用这个:
(function(){
//Bunch of code...
})();
在这:
//Bunch of code...
在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…
其他回答
可能是范围隔离。这样函数声明中的变量就不会污染外部命名空间。
当然,在一半的JS实现中,它们都是如此。
你可以使用这个函数返回值:
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#的“类”。
该函数可以定义局部变量,并在其中包含函数。内部函数(实际上是实例方法)可以访问局部变量(实际上是实例变量),但它们将与脚本的其余部分隔离。
下面是一个实例,说明了自我调用匿名函数的用处。
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());
在节点。插入是某种异步操作。
我不能只是调用等待没有异步关键字在我的函数的声明,我不需要一个命名函数以后使用,但需要等待插入调用或我需要一些其他更丰富的功能(谁知道?)。