代码之家  ›  专栏  ›  技术社区  ›  Steve Hanov

为什么许多JavaScript库以“(函数())”开头?

  •  13
  • Steve Hanov  · 技术社区  · 15 年前

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

    (function () { 
        /* code goes here */ 
    })();
    

    它似乎定义了一个未命名的函数,该函数被立即调用。为什么要这么做?

    5 回复  |  直到 15 年前
        1
  •  17
  •   vava    15 年前

    这是在JavaScript中进行名称间距的标准方法。如果你只是声明

    var my_cool_variable = 5;
    

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

    但是,如果你这样做了

    (function() {
        var my_cool_variable = 5;
    })();
    

    它现在是匿名函数的局部变量,在该函数的作用域之外不可见。您仍然可以通过不声明 var 在变量前面,这样它将是全局的,但现在您有了一个选择。

        2
  •  7
  •   kemiller2002    15 年前

    如果强制范围声明。通过将其放入函数中,可以确保创建和调用的变量不会被重新声明,或者不会意外调用在其他地方声明的变量。

    所以…

    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.
    }
    

    下面是一个链接,指向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.  
    
       }
    
    }
    
        3
  •  2
  •   John Parker    15 年前

    在一个简单的级别上,它保持全局命名空间的干净(ER)。

    也就是说,它有效地增加了一层围绕库中的函数和变量的包装层,从而确保不会与其他库中使用的其他函数发生任何命名空间冲突,等等。

        4
  •  1
  •   Sean Devlin    15 年前

    javascript没有块范围,只有函数范围。通过创建并立即调用匿名函数,我们可以保证它的局部变量不会跨过全局命名空间。这基本上是一种限制与其他图书馆之间冲突的方法。

        5
  •  0
  •   Samir Talwar PruthviRaj Reddy    15 年前
    var $={} // a name space is defined 
    
    (function($) {
            $.a_variable="some vale"
            var b_variable = "some more value";
    })($);
    
    $.a_variable // acess it like this.
    

    现在匿名函数中的任何东西的作用域都只等于该函数 此外,我们还可以创建可以作为名称空间属性的对象。