Javascript 简明教程

JavaScript - Self-Invoking Functions

Self-Invoking Functions

自调用函数是 JavaScript 函数,在定义时会立即执行。要定义自调用函数,你可以将匿名函数括在圆括号内,后面跟另一组圆括号。这些函数也称为自执行匿名函数。

The self-invoking functions are JavaScript functions that execute immediately as they are defined. To define a self-invoking function, you can enclose an anonymous function within parentheses followed by another set of parentheses. These are also called self-executing anonymous functions.

位于第一对圆括号内的匿名函数实际上是使用函数表达式定义的函数。所以,自调用函数也称为立即可调用的函数表达式 (IIFE)。

The anonymous function inside the first pair of parentheses is basically a function defined with function expression. So a self-invoking function is also called immediately invoked function expression (IIFE).

Syntax

在 JavaScript 中定义自调用函数的语法如下 −

The syntax to define the self-invoking functions in JavaScript is as follows −

(function () {
   // function body
})();

函数定义包含在圆括号对中。结尾处的第二个圆括号对执行函数。

The function definition is enclosed inside the pair of parentheses. The second pair of parentheses at the end executes the function.

另一种语法如下 −

An alternative syntax is as follows −

(function () {
   // function body
}());

第一个语法更加清晰。

The first syntax is more clear.

Example

在下例中,我们使用自执行函数打印输出中的消息。

In the example below, we print the message in the output using the self-executing function.

<html>
<body>
   <p id = "output"> </p>
   <script>
      (function () {
	     document.getElementById("output").innerHTML =
	     "Self-invoked function is executed!";
      }());
   </script>
</body>
</html>
Self-invoked function is executed!

Self-Invoking Functions with Parameters

可以创建带有参数的自调用函数,并向其中传递参数。向全局对象(如 window 等)传递引用是一种常见做法。

You can create a self-invoking function with parameters and pass arguments to it. It is common practice to pass references to global objects such as window, etc.

(function (paras) {
   // function body
})(args);

paras 是匿名函数定义中的参数列表,而 args 是传递的参数。

The paras are the list of parameters in the definition of the anonymous function and the args are arguments passed.

Example

在以下示例中,我们创建了一个带有参数名称的匿名函数。我们已向其传递了一个参数。

In the below example, we created an anonymous function with a parameter name. We have passed an argument to it.

<html>
<body>
   <div id = "demo"></div>
   <script>
      const output = document.getElementById("demo");
      (function (name) {
         output.innerHTML = `Welcome to ${name}`;
      })("Tutorials Point !");
   </script>
</body>
</html>
Welcome to Tutorials Point !

Private Scope of Self-Invoking Functions

在自执行函数中定义的所有代码都保留在私有作用域中,不会污染全局作用域。因此,开发人员可以使代码清晰,并消除命名冲突等错误。此外,自调用函数的代码仍然是隐藏的,其他部分代码无法访问。

Whatever code is defined inside the self-executing function remains in the private scope and doesn’t pollute the global scope. So, developers can make code clear and remove the errors like naming conflicts, etc. Also, the code of the self-invoking function remains hidden and can’t be accessible by other parts of the code.

Example

在以下示例中,我们在函数之外或函数内部定义变量“a”。在外部定义的变量是全局变量,在函数内部定义的变量是私有变量,仅限于自执行函数的作用域。

In the example below, we have defined the variable 'a' outside or inside the function. The variable defined outside is a global variable, and the variable defined inside the function is a private variable, limited to the self-executing function’s scope.

此外,我们已从函数的内部和外部打印了该变量的值。用户可以观察输出中的变量值。

Also, we have printed the value of the variable from inside and outside of the function. Users can observe the variable’s value in the output.

通过这种方式,我们可以避免命名冲突。

In this way, we can avoid the naming conflicts.

<html>
<body>
   <div id = "output"> </div>
   <script>
      const output = document.getElementById("output");
      let a = 10;
         (function () {
            output.innerHTML += "Entering to the function <br/>";
            var a = 20;
            output.innerHTML += "The value of a is " + a + "<br>";
            output.innerHTML += "Exiting to the function <br/>";
         }());
         output.innerHTML += "The value of the outside the function is " + a;
    </script>
</body>
</html>
Entering to the function
The value of a is 20
Exiting to the function
The value of the outside the function is 10

Example

在某些情况下,需要在函数外部访问自执行函数的变量。在这种情况下,我们可以使用 'window' 对象使该变量成为全局变量,如下所示,然后在全局作用域中访问该变量。

In some cases, it is required to access the variable of the self-executing function outside of the function. In this case, we can make that variable global using the 'window' object as shown below and access the variable in the global scope.

<html>
<body>
   <div id = "output"> </div>
   <script>
      (function () {
         var string = "JavaScript";
         window.string = string;
      })();
      document.getElementById("output").innerHTML =
	  "The value of the string variable is: " + string;
   </script>
</body>
</html>
The value of the string variable is: JavaScript

可以通过使用 call() 或 apply() 方法访问自调用函数的私有作用域。

Private scope of a self-invoking function can be accessed by using the call() or apply() methods.

Benefits of Using the Self-Invoking Functions

  1. Avoiding the global scope − Developers can avoid the global scope for variables and functions using the self-invoking function, helping to avoid naming conflict and making code more readable.

  2. Initialization − The self-executing functions can be used for the initialization of variables.

  3. Code privacy − Programmers can avoid accessing the code of the self-executing function by other parts of the code.