need more explanation on w3schools javascript closure example

被刻印的时光 ゝ 提交于 2019-12-02 01:12:18

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?)

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