我想知道这是什么意思:

(function () {

})();

这是在说document。onload吗?


当前回答

使用自调用匿名函数的原因是它们永远不应该被其他代码调用,因为它们“设置”了要调用的代码(同时为函数和变量提供了作用域)。

换句话说,它们就像在程序开始时“创建类”的程序。在它们被实例化(自动)之后,唯一可用的函数是匿名函数返回的那些函数。然而,所有其他“隐藏”函数仍然存在,以及任何状态(在作用域创建期间设置的变量)。

非常酷。

其他回答

这里已经有很多很好的答案了,但这里是我的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);

从这里开始:

var b = 'bee';
console.log(b);  // global

把它放在一个函数中,它就不再是全局的了——这是你的主要目标。

function a() {
  var b = 'bee';
  console.log(b);
}
a();
console.log(b);  // ReferenceError: b is not defined -- *as desired*

立即调用函数——哎呀:

function a() {
  var b = 'bee';
  console.log(b);
}();             // SyntaxError: Expected () to start arrow function, but got ';' instead of '=>'

使用括号来避免语法错误:

(function a() {
  var b = 'bee';
  console.log(b);
})(); // OK now

你可以省略函数名:

(function () {    // no name required
  var b = 'bee';
  console.log(b);
})();

不需要比这更复杂了。

该构造称为立即调用函数表达式(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限制在我们用花括号{…}创建的代码块中。

我称之为“卷毛监狱”。

这是一个更深入的解释,为什么你会使用这个:

“使用IIFE的主要原因是确保数据隐私。因为JavaScript的var将变量限定在包含变量的函数内,所以任何在IIFE中声明的变量都不能被外部世界访问。”

http://adripofjavascript.com/blog/drips/an-introduction-to-iffes-immediately-invoked-function-expressions.html

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

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

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

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