What is the exact definition of a closure?

后端 未结 8 1112
执念已碎
执念已碎 2020-11-28 09:43

I\'ve read through previous topics on closures on stackflow and other sources and one thing is still confusing me. From what I\'ve been able to piece together technically a

8条回答
  •  渐次进展
    2020-11-28 10:12

    A closure is an implementation technique for representing procedures/functions with local state. One way to implement closures is described in SICP. I will present the gist of it, anyway.

    All expressions, including functions are evaluated in an environement, An environment is a sequence of frames. A frame maps variable names to values. Each frame also has a pointer to it's enclosing environment. A function is evaluated in a new environment with a frame containing bindings for it's arguments. Now let us look at the following interesting scenario. Imagine that we have a function called accumulator, which when evaluated, will return another function:

    // This is some C like language that has first class functions and closures.
    function accumulator(counter) {
        return (function() { return ++counter; });
    }
    

    What will happen when we evaluate the following line?

    accum1 = accumulator(0);
    

    First a new environment is created and an integer object (for counter) is bound to 0 in it's first frame. The returned value, which is a new function, is bound in the global environment. Usually the new environment will be garbage collected once the function evaluation is over. Here that will not happen. accum1 is holding a reference to it, as it needs access to the variable counter. When accum1 is called, it will increment the value of counter in the referenced environment. Now we can call accum1 a function with local state or a closure.

    I have described a few practical uses of closures at my blog http://vijaymathew.wordpress.com. (See the posts "Dangerous designs" and "On Message-Passing").

提交回复
热议问题