JavaScript Tutorial - Pointers to Functions

Left
Right

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

<HTML>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
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("<PRE>");
document.writeln("add:3 + 4 =", add(3,4));
document.writeln("f:  3 + 4 =", f(3,4));
document.writeln("</PRE>");

document.writeln("<PRE>");
// 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);
document.writeln("</PRE>");
</SCRIPT>
</BODY>
</HTML>

HOMEWORK:

  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.
Left
Right
Slide 7