A closure is a function returned from a function complete with external variables.
The entire contents of an inner function will still be available outside the outermost function.
function simpleClosure () {
var x = 4;
function closeX (){
return x; // The inner function can access outer functions variable as if they were global variables.
}
return closeX;
}
// simpleClosure is finished but it's local variable, x, lives on.
var checkLocalX = simpleClosure();
checkLocalX(); // returns 4
Closures are useful in creating function factories.
function makePizza ( topping ) {
return function ( name ) {
alert("Making a " + topping + " pizza for " + name + ".");
}
}
var orderCheesePizza = makePizza("Cheese");
var orderAnchovyPizza = makePizza("Anchovy");
var orderPizzaPizza = makePizza("Pizza");
// The pizza topping is closed into the returned anonymous function.
orderCheesePizza("Chuck");
orderAnchovyPizza("Ralph");
orderPizzaPizza("Caesar");
// Calling makePizza with local variables for "name".
Closure functions can modify bound variables in the background. That is, even though the local scope has disappeared, the local variable retains it's value over multiple calls. Consider the following that adds a counter to the makePizza function.
function makePizza ( topping ) {
var pizzaCount = 0;
return function ( name ) {
pizzaCount++;
alert("Making a " + topping + " pizza for " + name + "./n" +
"We've made " + pizzaCount + " pizza's today!" );
}
}
Closures bind values at the last moment. The function's return
is when the closure occurs.
Most mistakes occur when executing loops, eg, returning values after a loop has completed instead of returning the value once the condition occurs.