我想知道这是什么意思:

(function () {

})();

这是在说document。onload吗?


当前回答

不,这个构造只是为命名创建了一个作用域。如果你把它分成几部分,你可以看到你有一个外部

(...)();

这是一个函数调用。括号内是:

function() {}

这是一个匿名函数。在构造中使用var声明的所有内容将只在同一构造中可见,并且不会污染全局名称空间。

其他回答

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

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

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

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

从这里开始:

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

不需要比这更复杂了。

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

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

非常酷。

自执行函数通常用于封装上下文和避免名称混淆。在(function(){..})()中定义的任何变量都不是全局变量。

的代码

var same_name = 1;

var myVar = (function() {
    var same_name = 2;
    console.log(same_name);
})();

console.log(same_name);

产生如下输出:

2
1

通过使用这种语法,可以避免与JavaScript代码中其他地方声明的全局变量发生冲突。