我正在尝试理解闭包并正在查看 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
变量被提升为匿名函数上下文,因此您可以从当前范围访问该变量。
这张图或多或少解释了这一点:
在这种情况下,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/