I asked a question about Currying and closures were mentioned. What is a closure? How does it relate to currying?
• 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) +
″
″);