为什么许多javascript库以"(function(){"开头?

Ste*_*nov 13 javascript

为什么许多javascript库看起来像这样:

(function () { 
    /* code goes here */ 
})();
Run Code Online (Sandbox Code Playgroud)

它似乎定义了一个立即调用的未命名函数.为什么要经历这种努力?

vav*_*ava 17

这是在JavaScript中执行命名空间的标准方法.如果你只是申报

var my_cool_variable = 5;
Run Code Online (Sandbox Code Playgroud)

它将是全局的,并且可能与使用相同变量的其他库冲突.

但是,如果你这样做

(function() {
    var my_cool_variable = 5;
})();
Run Code Online (Sandbox Code Playgroud)

它现在是匿名函数的局部变量,在该函数范围之外是不可见的.您仍然可以通过不在var变量前面声明来公开可访问的API ,这样它将是全局的,但现在您可以选择.


kem*_*002 7

如果力量范围声明.通过将它放在一个函数中,您确保您创建和调用的变量没有被重新声明,或者您不会意外地调用在其他地方声明的变量.

所以.....

var variable = 5; // this is accessible to everything in the page where:

function ()
{
   var variable = 7 // this is only available to code inside the function.
}
Run Code Online (Sandbox Code Playgroud)

这是一个链接到Douglas Crockford的网站,讨论Javascript中的范围:

http://javascript.crockford.com/code.html

跟进以下评论:

JavaScript的范围有点"破碎":

function ()
{
   var x = 3;  // accessible in the entire function.
   //for scope reasons, it's better to put var y = 8 here.....
   if(x != 4)
   {
       var y = 8; //still accessible in the entire function. 
                  //In other languages this wouldn't be accessible outside 
                  //of the if statement, but in JavaScript it is.  

   }

}
Run Code Online (Sandbox Code Playgroud)