From Wikibooks, open books for an open world
Jump to navigation Jump to search

In programming languages having first-class functions, closures (that are also called function closures or lexical closures) are a technique for implementing lexically-scoped name binding. Concerning its operation, a closure is nothing but a data structure storing a function together with an environment, which maps all associating each free variable of the function (that are used locally, but defined in an enclosing scope) with the value or storage location the name was bound to at the time the closure was created. A closure allows the function to access those captured variables through the closure's reference to them, even when the function is invoked outside its scope.

More technically, a closure is a stack frame of a function that is not deallocated when it returns.[1]

Examples[edit | edit source]

function sayHello(name) {
    var text = 'Hello, ' + name + '!';
    var sayAlert = function() { alert(text); }
    return sayAlert;
var say = sayHello('John');

alert(say.toString());    // Returns the code of the anonymous function

The function reference variable say references to both the function that alerts and to its closure! The closure is created by JavaScript, as the anonymous function is created inside another function. As the anonymous function needs its variables and those "inherited" from its enclosing function, the closure is necessary to provide it with these data. It is also possible to visualise the code of the function (see the last alert statement).

What makes it difficult to understand to many people is that in JavaScript, a function reference has also a hidden reference to the closure it was created in. This is similar to delegates that are a method pointer plus a secret reference to an object.

See also[edit | edit source]

Further reading[edit | edit source]

References[edit | edit source]