65.9K
CodeProject is changing. Read more.
Home

Function Pointers in JScript

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.63/5 (12 votes)

Apr 11, 2002

CPOL

1 min read

viewsIcon

90623

Basic overview of function variables in jscript

Introduction

Unless you're from a C/C++ background, function pointers/variables might seem like a strange concept. Basically, a function pointer is just like any other variable out there, but instead of pointing to an integer or string type, it points to the actual function. Bruce Eckel defines a function pointer as: "Once a function is compiled and loaded into the computer to be executed, it occupies a chunk of memory. That memory, and thus the function, has an address".

To illustrate this, here's a basic usage example.

function dostuff()
{
	return 'stuff';
}
var fnpointer=dostuff; //line 5
alert(fnpointer()); // line 6

As you can see, there really isn't anything difficult about the source code itself. If you have a closer look at the code, you'll see that line 5 is creating a variable fnpointer of type dostuff. Now, obviously, this isn't one of the JScript intrinsic type. The variable fnpointer is actually referencing the function dostuff and is used as a direct call to dostuff() would be ( viz Function(param1, param2) ).

Here's an example where parameters are being used:

function dostuff(sblah)
{
	return 'stuff' + sblah;
}
var fnpointer=dostuff;
alert(fnpointer(' mkay')); //line 6

The variable fnpointer acts just like the function does. So what's the point? ... Well, callbacks now become a possibility.

What you can also do is pass a function variable to a function and the function will be able to call the function this function variable points to, without much knowledge about the actual function. One thing that true OO languages would do at this point is use interfaces. JScript doesn't have these. Here's an elementary example of this:

function myfnvar()
{
	alert('you called the function variable');
}
function realfunction(ofnvar)
{
	ofnvar();
}
realfunction(myfnvar);

Pretty cool, huh?