我想知道这是什么意思:

(function () {

})();

这是在说document。onload吗?


当前回答

(function () {
})();

这被称为IIFE(立即调用函数表达式)。它是著名的JavaScript设计模式之一,是现代Module模式的核心和灵魂。顾名思义,它在创建后立即执行。此模式创建一个隔离的或私有的执行范围。

在ECMAScript 6之前的JavaScript使用词法作用域,因此IIFE用于模拟块作用域。(在ECMAScript 6中,通过引入let和const关键字,块范围是可能的。) 关于词汇范围问题的参考

用IIFE模拟块作用域

使用IIFE的性能优势是能够通过减少范围查找来将常用的全局对象(如window、document等)作为参数传递。(请记住,JavaScript在局部作用域和全局作用域的链中寻找属性)。因此,在局部作用域中访问全局对象可以减少查找时间,如下所示。

(function (globalObj) {
//Access the globalObj
})(window);

其他回答

从这里开始:

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

不需要比这更复杂了。

也就是说立即执行。

所以如果我这样做:

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

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

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

这里有一个例子:

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

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

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

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

非常酷。