need more explanation on w3schools javascript closure example

前端 未结 1 1729
既然无缘
既然无缘 2021-01-23 04:47

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





        
1条回答
  •  生来不讨喜
    2021-01-23 05:06

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

    0 讨论(0)
提交回复
热议问题