need more explanation on w3schools javascript closure example

故事扮演 提交于 2019-12-31 02:54:11

问题


I'm trying to understand closures and am looking at the W3Schools javascript tutorial. This is one example they give by making a counter.

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

The explanation isn't bad, but a few things are unclear. Why was a self invoking function the best thing to use? Why is the nested anonymous function not the self invoking function? And why do you have to return the whole anonymous function when the counter is already returned inside of it?


回答1:


The concept of closures could be explained as having functions and their contexts. A context is somewhat a kind of storage attached to the function to resolve variables captured (thus named closure?).

When the example code is executed:

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

You create a context where the counter variable is promoted to the anonymous function context thus you can access that variable from the current scope.

This diagram more or less explains it:

In this case, X and Y are captured by the function context and that is carried over all the executions of that function.

Now, this is just the V8 implementation of lexical environments.

See Vyacheslav Egorov great explanation on closure implementations using V8: Grokking V8 closures for fun (and profit?)



来源:https://stackoverflow.com/questions/35658731/need-more-explanation-on-w3schools-javascript-closure-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!