The purpose of closures
is simply to preserve state; hence the name closure
- it closes over state.
For the ease of further explanation, I'll use Javascript.
Typically you have a function
function sayHello(){
var txt="Hello";
return txt;
}
where the scope of the variable(s) is bound to this function. So after execution the variable txt
goes out of scope. There is no way of accessing or using it after the function has finished execution.
Closures are language construct, which allow - as said earlier - to preserve the state of the variables and so prolong the scope.
This could be useful in different cases. One use case is the construction of higher order functions.
In mathematics and computer science, a higher-order function (also functional form, functional or functor) is a function that does at least one of the following:1
- takes one or more functions as an input
- outputs a function
A simple, but admittely not all too useful example is:
makeadder=function(a){
return function(b){
return a+b;
}
}
add5=makeadder(5);
console.log(add5(10));
You define a function makedadder
, which takes one parameter as input and returns a function. There is an outer function function(a){}
and an inner function(b){}{}
.Further you define (implicitely) another function add5
as the result of calling the higher order funtion makeadder
. makeadder(5)
returns an anonymous (inner) function, which in turn takes 1 parameter and returns the sum of the parameter of the outer function and the parameter of the inner function.
The trick is, that while returning the inner function, which does the actual adding, the scope of the parameter of the outer function (a
) is preserved. add5
remembers, that the parameter a
was 5
.
Or to show one at least somehow usefull example:
makeTag=function(openTag, closeTag){
return function(content){
return openTag +content +closeTag;
}
}
table=makeTag("<table>","</table>")
tr=makeTag("<tr>", "</tr>");
td=makeTag("<td>","</td>");
console.log(table(tr(td("I am a Row"))));
Another common usecase is the so called IIFE = immediately invoked function expression.
It is very common in javascript to fake private member variables. This is done via a function, which creates a private scope = closure
, because it is immediatly after definition invoked. The structure is function(){}()
. Notice the brackets ()
after the definition.
This makes it possible to use it for object-creation with revealing module pattern.
The trick is creating a scope and returning an object, which has access to this scope after execution of the IIFE.
Addi's example looks like this:
var myRevealingModule = (function () {
var privateVar = "Ben Cherry",
publicVar = "Hey there!";
function privateFunction() {
console.log( "Name:" + privateVar );
}
function publicSetName( strName ) {
privateVar = strName;
}
function publicGetName() {
privateFunction();
}
// Reveal public pointers to
// private functions and properties
return {
setName: publicSetName,
greeting: publicVar,
getName: publicGetName
};
})();
myRevealingModule.setName( "Paul Kinlan" );
The returned object has references to functions (e.g. publicSetName
), which in turn have access to "private" variables privateVar
.
But these are more special use cases for Javascript.
What specific task would a programmer be performing that might be best served by a closure?
There are several reasons for that. One might be, that it is natural for him, since he follows a functional paradigm. Or in Javascript: it is mere necessity to rely on closures to circumvent some quirks of the language.