Java Reference

In-Depth Information

Generalized Functions

Callbacks can be used to build more generalized functions. Instead of having lots of spe-

cific functions, one function can be written that accepts a callback. For example, we could

add a callback parameter to the
random()
function, so that a calculation is performed on

the random number that's returned:

function random(a,b,callback) {

if (b === undefined) b = a, a = 1; // if only one

argument is

↵
supplied, assume the lower limit is 1

result = Math.floor((b-a+1) * Math.random()) + a

if(typeof callback === "function") {

result = callback(result);

}

return result;

}

Now we have a function where more flexibility can be added using a callback. For ex-

ample, we can have a random square number from one to 100:

random(1,10,square);

<< 49

Or a random even number from two to ten:

random(1,5, function(n) { return 2 * n });

<< 8