November 4, 1999 - Function References | WebReference

November 4, 1999 - Function References

Yehuda Shiran November 4, 1999
Function References
Tips: November 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

All functions in JavaScript are objects, so a function reference is actually an object reference. Take a look at the following example:

function multiply(op1, op2) {
  return op1 * op2;
}
var test = multiply;
alert(test(3, 4));

As you can see, a function reference can be handed to a variable. The function can then be executed by invoking that variable via a set of parentheses. This technique can be very convenient for easy-to-follow cross-browser scripts. Here's a demonstration:

function nsFunction() {
  // Navigator statements
}
function ieFunction() {
  // Internet Explorer statements
}
var crFunction = (document.all) ? ieFunction : nsFunction;
crFunction();

In some situations, only function references are accepted. For example, a constructor function that creates a custom object must assign a function reference to its method specifications:

function multiply(op1, op2) {
  return op1 * op2;
}
function divide(op1, op2) {
  return op1 / op2;
}
function myMath() {
  this.mul = multiply;
  this.div = divide;
}
var operations = new myMath();
alert(operations.mul(4, 10)); // alerts "40"

Event handlers specified as properties also require function references:

function hello() {
  alert("Hello!");
}
window.onload = hello;