在javascript中,什么时候你想使用这个:
(function(){
//Bunch of code...
})();
在这:
//Bunch of code...
在javascript中,什么时候你想使用这个:
(function(){
//Bunch of code...
})();
在这:
//Bunch of code...
当前回答
命名空间。JavaScript的作用域是函数级的。
其他回答
这都是关于变量作用域的。默认情况下,在自执行函数中声明的变量仅可用于自执行函数中的代码。这允许编写代码时不考虑变量在其他JavaScript代码块中的命名方式。
例如,正如Alexander在评论中提到的:
(函数(){ Var foo = 3; console.log (foo); }) (); console.log (foo);
这将首先记录3,然后在下一个console.log上抛出一个错误,因为foo没有定义。
此方法用于闭包。有关闭包的更多信息,请阅读此链接。
IIRC允许你创建私有属性和方法。
自调用函数在javascript:
自动调用(启动)自调用表达式,而不需要调用。自调用表达式在创建后立即被调用。这主要用于避免命名冲突以及实现封装。变量或声明的对象在此函数之外不可访问。为了避免最小化(filename.min)的问题,总是使用自执行函数。
你可以使用这个函数返回值:
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) );