JavaScript 自执行函数



自执行函数

自执行函数是在定义时立即执行的 JavaScript 函数。要定义自执行函数,可以将匿名函数用括号括起来,然后后面再跟一对括号。这些函数也称为自执行匿名函数。

第一对括号内的匿名函数基本上是用函数表达式定义的函数。因此,自执行函数也称为立即调用函数表达式 (IIFE)。

语法

在 JavaScript 中定义自执行函数的语法如下:

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

函数定义包含在一对括号中。末尾的第二对括号执行该函数。

另一种语法如下:

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

第一种语法更清晰。

示例

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

<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!

带参数的自执行函数

您可以创建带参数的自执行函数,并将参数传递给它。常见的做法是传递对全局对象的引用,例如 window 等。

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

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

示例

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

<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 !

自执行函数的私有作用域

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

示例

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

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

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

<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

示例

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

<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() 方法访问自执行函数的私有作用域。

使用自执行函数的好处

  • 避免全局作用域 - 开发人员可以使用自执行函数避免变量和函数的全局作用域,有助于避免命名冲突并使代码更易于阅读。

  • 初始化 - 自执行函数可用于变量的初始化。

  • 代码私有性 - 程序员可以防止其他代码部分访问自执行函数的代码。

广告
© . All rights reserved.