Since functions are objects in JavaScript, you can define an array of them quite easily.
function foo () { ... }
function bar () { ... }
function baz () { ... }
var fns = [foo, bar, baz];
The signature does not matter at all.
From there you can start dynamically generating functions in a loop, rather than explicitly declaring each one:
function generator(n)
{
return function ()
{
return n*n;
};
}
var squareFuncs = [];
for (var i=0; i<10; i++)
{
squareFuncs.push(generator(i));
}
Then you can build up arrays of arrays of functions (just like any other object, remember):
function anotherGenerator(a, b)
{
return function ()
{
return a+b;
};
}
var sumFuncs = [],
temp,
i,
j;
for (i=0; i<20; i++)
{
temp = [];
for (j=0; j<20; j++)
{
temp.push(anotherGenerator(i, j));
}
sumFuncs.push(temp);
}
Now sumFuncs
is a two-dimensional array (really, an array of arrays) of functions which compute the sum of the coordinates of that function in the matrix. That probably sounds more complicated than it really is, so here's an example:
var foo = sumFuncs[7][2],
sum = foo();
console.log(sum); // prints 9
Related: