我想知道这是什么意思:

(function () {

})();

这是在说document。onload吗?


当前回答

还有一个用例是内存,缓存对象不是全局的:

var calculate = (function() {
  var cache = {};
  return function(a) {

    if (cache[a]) {
      return cache[a];
    } else {
      // Calculate heavy operation
      cache[a] = heavyOperation(a);
      return cache[a];
    }
  }
})();

其他回答

该构造称为立即调用函数表达式(IIFE),这意味着它将立即执行。可以把它看作是解释器到达该函数时自动调用的函数。

最常见的用例:

它最常见的用例之一是限制通过var创建的变量的作用域。通过var创建的变量的作用域仅限于一个函数,因此这个构造(这是一个围绕某些代码的函数包装器)将确保你的变量作用域不会泄漏到该函数中。

在下面的例子中,count在立即调用的函数之外是不可用的,即count的作用域不会泄漏到函数之外。您应该得到一个ReferenceError,如果您尝试在立即调用的函数之外访问它。

(function () { 
    var count = 10;
})();
console.log(count);  // Reference Error: count is not defined

ES6备选方案(推荐)

在ES6中,我们现在可以通过let和const创建变量。它们都是块范围的(不像var是函数范围的)。

因此,对于上面提到的用例,您不必使用IIFE的复杂构造,现在可以编写更简单的代码,以确保变量的作用域不会泄漏到所需的块中。

{ 
    let count = 10;
}
console.log(count);  // ReferenceError: count is not defined

在本例中,我们使用let定义count变量,使count限制在我们用花括号{…}创建的代码块中。

我称之为“卷毛监狱”。

它声明了一个匿名函数,然后调用它:

(function (local_arg) {
   // anonymous function
   console.log(local_arg);
})(arg);

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

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

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

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

$(function(){
});

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

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

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

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”现在是一个局部变量。

在ES6语法中(为自己发帖,因为我一直登陆这个页面寻找一个快速的例子):

// simple
const simpleNumber = (() => {
  return true ? 1 : 2
})()

// with param
const isPositiveNumber = ((number) => {
  return number > 0 ? true : false
})(4)