*** Welcome to piglix ***

Closure (computer programming)


In programming languages, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function together with an environment: a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created. A closure—unlike a plain function—allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

Example. The following program fragment defines a higher-order function startAt with a parameter x and a nested function incrementBy. The nested function incrementBy has access to x, because incrementBy is in the lexical scope of x, even though x is not local to incrementBy. The function startAt returns a closure containing a copy of the value of x or a copy of the reference to x from this invocation of startAt, and the function incrementBy, which adds the value of y to the value of x:

Note that, as startAt returns a function, the variables closure1 and closure2 are of function type. Invoking closure1(3) (Meaning y=3) will return 4, while invoking closure2(3) (Meaning y=3) will return 8. While closure1 and closure2 refer to the same function incrementBy, the associated environments differ, and invoking the closures will bind the name x to two distinct variables with different values in the two invocations, thus evaluating the function to different results.


...
Wikipedia

...