我想知道这是什么意思:

(function () {

})();

这是在说document。onload吗?


当前回答

它只是一个匿名函数,在创建后立即执行。

这就像你把它赋值给一个变量,然后在后面使用它,只是没有变量:

var f = function () {
};
f();

在jQuery中,有一个类似的构造,你可能会想到:

$(function(){
});

这是绑定就绪事件的简写形式:

$(document).ready(function(){
});

但是上面的两个结构都不是iife。

其他回答

立即调用函数表达式(IIFE)是一种在创建时立即执行的函数。它与任何事件或异步执行没有关联。你可以定义一个IIFE,如下所示:

(function() {
     // all your code here
     // ...
})();

第一对括号函数(){…}将括号内的代码转换为表达式。第二对括号调用由表达式生成的函数。

IIFE也可以描述为一个自我调用的匿名函数。它最常见的用法是限制通过var创建的变量的作用域,或者封装上下文以避免名称冲突。

这里已经有很多很好的答案了,但这里是我的2美分:p


你可以使用IIFE(立即调用函数表达式):

Avoiding pollution in the global namespace. Variables defined in IIFE (or even any normal function) don't overwrite definitions in global scope. Protecting code from being accessed by outer code. Everything that you define within the IIFE can be only be accessed within the IIFE. It protects code from being modified by outer code. Only what you explicitly return as the result of function or set as value to outer variables is accessible by outer code. Avoid naming functions that you don't need to use repeatedly. Though it's possible to use a named function in IIFE pattern you don't do it as there is no need to call it repeatedly, generally. For Universal Module Definitions which is used in many JS libraries. Check this question for details.


IIFE通常以以下方式使用:

(function(param){
   //code here
})(args);

您可以省略匿名函数周围的括号(),并在匿名函数之前使用void运算符。

void function(param){
   //code here
}(args);

以下代码:

(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的函数括号内。这减少了命名冲突的可能性,让你在命名时更粗心(例如,你不必在它们前面加上前缀)。

通常,我们不会在程序中写入函数后立即调用它。 简单来说,当您在函数创建后立即调用它时,它被称为IIFE——一个漂亮的名字。

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

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

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

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