为什么有些js文件以(function(){开头

Mak*_*ges 14 javascript function

简单,为什么一些js文件(如Ember或JQuery.js)开头(function() {...})();

Nie*_*sol 15

表单的代码(function() { /* code here */ })()称为"立即调用的函数表达式".它经常用于设置闭包,因此您可以定义变量而不会污染全局范围.你可以在Ember,jQuery和几乎所有其他"插件"中找到它.污染全局范围通常是一个坏主意,但是如果插件必须适用于所有站点,那么确保它不会意外覆盖站点创建者正在使用的变量尤为重要.

当然,还有其他用途.例如,它可以用来"锚定"一个迭代变量,如下所示:

for( i=0; i<links.length; i++) {
    (function(i) {
        links[i].onclick = function() {alert(i);};
    })(i);
}
// without the IIFE, all links would alert the value of links.length instead.
Run Code Online (Sandbox Code Playgroud)

还有一些情况我偶尔使用IIFE,大多数人可能会让我感到困惑,例如"及时"计算:

if( (function() {
      var party=document.getElementById('party').children, l=party.length, i, r=0;
      for( i=0; i<l; i++) if( party[i].children.length > 0) r++;
      return r;
  })() == 6) {
    // your Party is full
}
Run Code Online (Sandbox Code Playgroud)

如果在跳到if声明之前计算出上述内容会好得多,所以...不要像我在这个上做的那样做!


Pra*_*gat 7

语法以.开头

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

知道为立即调用匿名函数,该函数在最后一行代码后立即执行.用于确定其他函数的变量.

更多信息:http: //en.wikipedia.org/wiki/Immediately-invoked_function_expression