JavaScript 中的闭包是如何工作的?

WBOY
WBOY 转载
2023-08-24 21:05:04 515浏览

在本文中,我们将了解“闭包”以及它们在 JavaScript 中的实际工作原理。闭包基本上是一个函数的组合,该函数包含对其周围状态的引用(也称为词法环境)。

JavaScript 中,基本上每次在运行时创建函数时都会创建闭包。换句话说,闭包只是一个奇特的名称,它记住了内部使用的外部事物。

让我们通过一些示例来了解 JavaScript 闭包 -

示例 1 h2>

在下面的示例中,我们将声明一个闭包,最终能够从外部函数访问外部变量 tagLine

在最内部函数中使用外部变量后,这个特定的闭包将帮助用户在每次调用外部函数时提醒 tagLine。

#Filename: index.html

<!DOCTYPE html>
<html>
<head>
   <title>
      Closures in Javascript
   </title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <button type="button" onclick="init()">
      Click here!!!
   </button>
   <p id="demo"></p>
<script>
   function init() {
      var tagLine = "Start your Learning journey now";
      function display() { // display() is the inner function, a closure
         alert(tagLine); // use variable declared in the parent function
      }
      display();
   }
   </script>
</body>
</html>

输出

这将产生以下结果。

JavaScript 中的闭包是如何工作的?

示例 2

在下面的示例中,我们使用嵌套闭包调用两个函数并显示同一函数的输出。

#文件名:index.html

<!DOCTYPE html>
<html>
<head>
   <title>
      Closures in Javascript
   </title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <button type="button" onclick=" Counter()">
      Click Me!
   </button>
   <p id="demo1"></p>
   <p id="demo2"></p>
<script>
function Counter() {
   var counter = 0;
   function outerfunction() {
   counter += 1;
   document.getElementById("demo1").innerHTML
      = "Outer Counter called = " + counter +" from Outer Function " ;
      function innerfunction() {
         counter += 1;
         document.getElementById("demo2").innerHTML
         = "Inner Counter called = " + counter +" from Inner Function ";
      };
      innerfunction();
   };
   outerfunction();
};
</script>
</body>
</html>

输出

JavaScript 中的闭包是如何工作的?

以上就是JavaScript 中的闭包是如何工作的?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除