JavaScript Tutorial - Pointers to Functions


It's almost crazy to introduce the concept of pointers to functions here, but it's one of the most useful tools for advanced and object-oriented programming. You can pass functions as data!

This forms the basis of most parsers and some interactive tools which will be developed later.

The root concept is that you can set a variable to a function name, and later invoke that function via the variable. Carefully study the following
example: work/funcptr.html

function add(x,y)	{return x+y; }
function subtract(x,y)	{return x-y; }
function multiply(x,y)	{return x*y; }
function divide(x,y)	{return x/y; }
function operate(operator, x, y) { return operator(x,y); }

var f = add;	// this is a pointer to a function

document.writeln("add:3 + 4 =", add(3,4));
document.writeln("f:  3 + 4 =", f(3,4));

// notice that none of the arithmetic fns are called directly!
var r = operate(divide,
	operate(subtract, operate(multiply,5,6), operate(multiply,3,3)),7);
// also careful how you split lines!
// JavaScript can assume a statement has terminated
document.writeln("now we want to evaluate ((5*6) - (3*3))/7 = ",r);


  1. Use the functions defined in the last section F2C and C2F. For the value x=32 use the variable conv as a pointer to the first conversion function, output the value returned for conv(x). Set conv to the second conversion function and repeat the output statement.
Slide 7