What is a 'Closure'?

前端 未结 23 1555
星月不相逢
星月不相逢 2020-11-22 08:02

I asked a question about Currying and closures were mentioned. What is a closure? How does it relate to currying?

23条回答
  •  一整个雨季
    2020-11-22 08:54

    • A closure is a subprogram and the referencing environment where it was defined

    – The referencing environment is needed if the subprogram can be called from any arbitrary place in the program

    – A static-scoped language that does not permit nested subprograms doesn’t need closures

    – Closures are only needed if a subprogram can access variables in nesting scopes and it can be called from anywhere

    – To support closures, an implementation may need to provide unlimited extent to some variables (because a subprogram may access a nonlocal variable that is normally no longer alive)

    Example

    function makeAdder(x) {
    return function(y) {return x + y;}
    }
    var add10 = makeAdder(10);
    var add5 = makeAdder(5);
    document.write(″add 10 to 20: ″ + add10(20) +
    ″
    ″); document.write(″add 5 to 20: ″ + add5(20) + ″
    ″);

提交回复
热议问题