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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
HP to Microsoft: Thanks for Nothing
iPhone Remains Left Out as Android Scores Flash
The Year of Living the OpenSocial
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;


People who read this tip also read these tips:

Look for similar tips by subject:

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

webref The latest from WebReference.com Browse >
Administering RBAC in PHP 5 CMS Framework · xref: Automatic Cross Referencing Script · Book Review: Content Rich
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Gateway Launches New Core i7-powered FX-Series Gaming PCs · Review: Lenovo ThinkPad SL300 · EBay, Alternative Site Holiday Resources for Sellers