我想知道这是什么意思:

(function () {

})();

这是在说document。onload吗?


当前回答

以下代码:

(function () {

})();

称为立即调用函数表达式(IIFE)。

它之所以被称为函数表达式,是因为Javascript中的(yourcode)操作符将其强制转换为表达式。函数表达式和函数声明的区别如下:

// declaration:
function declaredFunction () {}

// expressions:

// storing function into variable
const expressedFunction = function () {}

// Using () operator, which transforms the function into an expression
(function () {})

表达式只是一组可以求值为单个值的代码。对于上面例子中的表达式,这个值是一个单独的函数对象。

在得到表达式后,计算结果为函数对象,然后可以立即使用()操作符调用函数对象。例如:

(函数(){ Const foo = 10;//这里的所有变量都是函数块的作用域 console.log (foo); }) (); console.log (foo);// referenceError foo的作用域是IIFE

为什么这个有用?

当我们处理大型代码库和/或导入各种库时,命名冲突的几率会增加。当我们在IIFE中编写相关(因此使用相同的变量)的代码的某些部分时,所有的变量和函数名都被限定在IIFE的函数括号内。这减少了命名冲突的可能性,让你在命名时更粗心(例如,你不必在它们前面加上前缀)。

其他回答

这个函数称为自调用函数。自调用(也称为自执行)函数是在定义之后立即调用(已调用)的无名(匿名)函数。点击这里阅读更多

这些函数的作用是,当函数被定义时,函数立即被调用,这节省了时间和额外的代码行(与在单独的行上调用相比)。

这里有一个例子:

(函数(){ Var x = 5 + 4; console.log (x); }) ();

这是一个自调用匿名函数。

查看W3Schools对自调用函数的解释。

函数表达式可以“自调用”。 自动调用(启动)自调用表达式,无需 被称为。 函数表达式将自动执行 后面跟着()。 不能自调用函数声明。

也就是说立即执行。

所以如果我这样做:

var val = (function(){
     var a = 0;  // in the scope of this function
     return function(x){
         a += x;
         return a;
     };
})();

alert(val(10)); //10
alert(val(11)); //21

小提琴:http://jsfiddle.net/maniator/LqvpQ/


第二个例子:

var val = (function(){
     return 13 + 5;
})();

alert(val); //18

自执行匿名函数。它在创建时立即执行。

举个简单的例子,说明这个方法很有用:

function prepareList(el){
  var list = (function(){
    var l = []; 
    for(var i = 0; i < 9; i++){
     l.push(i);
    }
    return l;
  })();

  return function (el){
    for(var i = 0, l = list.length; i < l; i++){
      if(list[i] == el) return list[i];
    }
    return null;
  }; 
} 

var search = prepareList();
search(2);
search(3);

因此,不是每次都创建一个列表,而是只创建一次(开销更少)。

Normally, JavaScript code has global scope in the application. When we declare global variable in it, there is a chance for using the same duplicate variable in some other area of the development for some other purpose. Because of this duplication there may happen some error. So we can avoid this global variables by using immediately invoking function expression , this expression is self-executing expression.When we make our code inside this IIFE expression global variable will be like local scope and local variable.

我们可以通过两种方式创建IIFE

(function () {
    "use strict";
    var app = angular.module("myModule", []);
}());

OR

(function () {
    "use strict";
    var app = angular.module("myModule", []);
})();

在上面的代码片段中,“var app”现在是一个局部变量。