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

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

在这:

//Bunch of code...

当前回答

首先你必须访问MDN IIFE,现在关于这一点有几点

这是立即调用的函数表达式。当你的javascript文件从HTML中调用这个函数时立即调用。 这防止了在IIFE习惯用法中访问变量以及污染全局作用域。

其他回答

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

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

一个区别是,你在函数中声明的变量是局部的,所以当你退出函数时,它们就消失了,并且它们不会与其他或相同代码中的其他变量冲突。

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

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

首先你必须访问MDN IIFE,现在关于这一点有几点

这是立即调用的函数表达式。当你的javascript文件从HTML中调用这个函数时立即调用。 这防止了在IIFE习惯用法中访问变量以及污染全局作用域。