javascript - 需要更多关于 w3schools javascript 闭包示例的解释

标签 javascript closures anonymous-function self-invoking-function

我正在尝试理解闭包并正在查看 W3Schools javascript 教程。这是他们通过制作计数器给出的一个例子。

<body>

<p>Counting with a local variable.</p>

<button type="button" onclick="myFunction()">Count!</button>

<p id="demo">0</p>

<script>
var add = (function () {
    var counter = 0;
     return function () {return counter += 1;}
})();

function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>

</body>

Example Explained The variable add is assigned the return value of a self-invoking function.

The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.

This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope.

This is called a JavaScript closure. It makes it possible for a function to have "private" variables.

The counter is protected by the scope of the anonymous function, and can only be changed using the add function.

Note A closure is a function having access to the parent scope, even after the parent function has closed.

解释还不错,但有几件事不清楚。为什么自调用函数是最好用的东西?为什么嵌套的匿名函数不是自调用函数?当计数器已经在其中返回时,为什么还必须返回整个匿名函数?

最佳答案

闭包的概念可以解释为具有函数及其上下文。上下文在某种程度上是一种附加到函数的存储,用于解析捕获的变量(因此命名为闭包?)。

执行示例代码时:

var add = (function () {
    var counter = 0; // This is promoted to the below's function context
    return function () {return counter += 1;}
})();

您创建一个上下文,其中 counter 变量被提升为匿名函数上下文,因此您可以从当前范围访问该变量。

这张图或多或少解释了这一点:

JS Functions and Context

在这种情况下,X 和 Y 由函数上下文捕获,并在该函数的所有执行过程中进行。

现在,这只是 lexical environments 的 V8 实现.

请参阅 Vyacheslav Egorov 关于使用 V8 实现闭包的精彩解释:Grokking V8 closures for fun (and profit?)

关于javascript - 需要更多关于 w3schools javascript 闭包示例的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35658731/

相关文章:

javascript - Three.js 通过 GUI 打开和关闭对象可见性

javascript - jQuery 在移动版 Safari 的 <a> 标签上显示

javascript - 锤子js : pinchend sometimes doesn't fire

Python序列化词法闭包?

javascript show hide div by id 问题

Javascript、内部类以及如何有效地访问父作用域

javascript - 扩展数组和闭包

c# - 匿名函数和局部变量

匿名函数中的javascript奇怪行为

matlab - 如何在 Simulink Matlab 功能 block 中使用 syms