Java Reference
In-Depth Information
A Functional Example
It's also possible to create a closure around the arguments provided to a function. This al-
lows us to create a generic function that can be used to then return more specific functions
based on its arguments. For example, consider this generic multiplier() function:
function multiplier(x){
return function(y){
return x*y;
}
}
This function returns another function that traps the argument x in a closure, which is then
used in the returned function. It can be used to create another function:
doubler = multiplier(2);
This creates a new function called doubler() that takes a parameter that's multiplied
by the argument provided to the multiplier() function—which was 2 in this
case—making a function that multiplies its argument by two:
doubler(10);
<< 20
This makes the multiplier() function a generic abstraction that can be used to build
more specific abstractions, such as a tripler() function:
tripler = multiplier(3);
tripler(10);
<< 30
Search WWH ::




Custom Search