Home >Web Front-end >JS Tutorial >JavaScript Closures
JavaScript closure is a powerful and important concept in JavaScript. It refers to a function, even after its external (closed) function is executed, it can still access variables of external functions. Closing is a key component of JavaScript scope and functional programming.
The working principle of closure
Closure example
<code class="language-javascript">function 外部函数() { let 外部变量 = '我来自外部作用域'; function 内部函数() { console.log(外部变量); // 内部函数可以访问外部变量 } return 内部函数; } const 闭包示例 = 外部函数(); 闭包示例(); // 输出: "我来自外部作用域"</code>In this example:
is a closure, because it still retains the access of
even after the 内部函数
execution is completed. 外部函数
外部变量
The actual application of closure
<code class="language-javascript">function 创建计数器() { let 计数 = 0; return function() { 计数++; return 计数; }; } const 计数器 = 创建计数器(); console.log(计数器()); // 输出: 1 console.log(计数器()); // 输出: 2 console.log(计数器()); // 输出: 3</code>: Closed is widely used for asynchronous programming, such as event processing program or AJAX calls.
<code class="language-javascript">setTimeout(function() { console.log('这是一个使用闭包的回调函数'); }, 1000);</code>
<code class="language-javascript">function 乘法(a) { return function(b) { return a * b; }; } const 乘以二 = 乘法(2); console.log(乘以二(5)); // 输出: 10</code>: Closure helps control the scope of variables to prevent them from polluting the global scope.
The above is the detailed content of JavaScript Closures. For more information, please follow other related articles on the PHP Chinese website!