我想知道这是什么意思:

(function () {

})();

这是在说document。onload吗?


当前回答

它是一个函数表达式,它代表立即调用函数表达式(IIFE)。IIFE只是一个在创建后立即执行的函数。因此,函数不必等到调用它才能执行,而是立即执行IIFE。让我们通过示例来构造IIFE。假设我们有一个add函数,它接受两个整数作为参数并返回和 让我们把add函数放到IIFE中,

步骤1:定义函数

function add (a, b){
    return a+b;
}
add(5,5);

Step2:通过将整个函数声明包装到圆括号中来调用函数

(function add (a, b){
    return a+b;
})
//add(5,5);

步骤3:要立即调用函数,只需从调用中删除'add'文本。

(function add (a, b){
    return a+b;
})(5,5);

使用IFFE的主要原因是在函数中保留私有作用域。在javascript代码中,你要确保你没有覆盖任何全局变量。有时您可能会意外地定义一个覆盖全局变量的变量。让我们举个例子。假设我们有一个名为iffe.html的HTML文件,body标签内的代码是-

<body>
    <div id = 'demo'></div>
    <script>
        document.getElementById("demo").innerHTML = "Hello JavaScript!";
    </script> 
</body>

好吧,上面的代码将毫无疑问地执行,现在假设您意外或有意地声明了一个名为document的变量。

<body>
    <div id = 'demo'></div>
    <script>
        document.getElementById("demo").innerHTML = "Hello JavaScript!";
        const document = "hi there";
        console.log(document);
    </script> 
</body>

你将会看到一个SyntaxError:重新声明不可配置的全局属性文档。

但是如果你想要声明一个名为documentmet的变量,你可以使用IFFE来实现。

<body>
    <div id = 'demo'></div>
    <script>
        (function(){
            const document = "hi there";
            this.document.getElementById("demo").innerHTML = "Hello JavaScript!";
            console.log(document);
        })();
        document.getElementById("demo").innerHTML = "Hello JavaScript!";
    </script> 
</body>

输出:

让我们尝试另一个例子,假设我们有一个计算器对象像bellow-

<body>
    <script>
        var calculator = {
            add:function(a,b){
                return a+b;
            },
            mul:function(a,b){
                return a*b;
            }
        }
        console.log(calculator.add(5,10));
    </script> 
</body>

这很神奇,如果我们不小心重新赋值了计算器对象的值。

<body>
    <script>
        var calculator = {
            add:function(a,b){
                return a+b;
            },
            mul:function(a,b){
                return a*b;
            }
        }
        console.log(calculator.add(5,10));
        calculator = "scientific calculator";
        console.log(calculator.mul(5,5));
    </script> 
</body>

是的,你将结束一个TypeError:计算器。Mul不是if .html的函数

但是在IFFE的帮助下,我们可以创建一个私有作用域,在那里我们可以创建另一个变量名计算器并使用它;

<body>
    <script>
        var calculator = {
            add:function(a,b){
                return a+b;
            },
            mul:function(a,b){
                return a*b;
            }
        }
        var cal = (function(){
            var calculator = {
                sub:function(a,b){
                    return a-b;
                },
                div:function(a,b){
                    return a/b;
                }
            }
            console.log(this.calculator.mul(5,10));
            console.log(calculator.sub(10,5));
            return calculator;
        })();
        console.log(calculator.add(5,10));
        console.log(cal.div(10,5));
    </script> 
</body>

输出:

其他回答

也就是说立即执行。

所以如果我这样做:

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

该构造称为立即调用函数表达式(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 -立即调用函数表达式。下面是一个例子来展示它的语法和用法。它用于将变量的使用范围限定在函数之前,而不是超出函数。

(function () {
  function Question(q,a,c) {
    this.q = q;
    this.a = a;
    this.c = c;
  }

  Question.prototype.displayQuestion = function() {
    console.log(this.q);
    for (var i = 0; i < this.a.length; i++) {
      console.log(i+": "+this.a[i]);
    }
  }

  Question.prototype.checkAnswer = function(ans) {
    if (ans===this.c) {
      console.log("correct");
    } else {
      console.log("incorrect");
    }
  }

  var q1 = new Question('Is Javascript the coolest?', ['yes', 'no'], 0);
  var q2 = new Question('Is python better than Javascript?', ['yes', 'no', 'both are same'], 2);
  var q3 = new Question('Is Javascript the worst?', ['yes', 'no'], 1);

  var questions = [q1, q2, q3];

  var n = Math.floor(Math.random() * questions.length)

  var answer = parseInt(prompt(questions[n].displayQuestion()));
  questions[n].checkAnswer(answer);
})();

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

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

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

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

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

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