Java Reference
In-Depth Information
return c * a + b;
}
}
Now a new function can be created by invoking this function and assigning the return value
to a variable:
toFahrenheit = closure();
This new function can then be invoked with its own argument, but the values of
a
and
b
from the original function are still remembered:
toFahrenheit(30);
<< 86
A Counter Example
Closures not only maintain the value of a variable from another function; this value can
also be subsequently changed. It can be used to create a
counter()
function that starts a
count using the variable
i
. It then returns a function that uses a closure to trap the value of
i
, which can then be incremented every time the new function is invoked. The reference to
the variable
i
that is defined in the original function is maintained in the new function via
a closure:
function counter(start){
i = start;
return function() {
return i++;
}
}
var count = counter(1); // start a counter at 1
count();
<< 1
count();
<< 2
