Wednesday, November 09, 2005

Function Pointers in Javascript

One of the most powerful features of the JavaScript language is every data type is treated as an object. The JavaScript datatypes include numbers, strings, arrays, objects, and functions. While most of these variable types should be familiar to JavaScript programmers, it is the function data type that is the most often confused and misunderstood. Below we show you how JavaScript treats a function no different than any other data type.

var stringDemo = "This is a string"
var functionDemo = new Function("alert('I am a function!');return false")

document.write("<B>" + typeof stringDemo + "</B><BR>" + stringDemo)

document.write("<BR><B>" + typeof stringDemo + "</B><BR>" + functionDemo)

Running the above code generates the following output:

This is a string

function anonymous() { alert("I am a function!"); }

In this example we did not execute the functionDemo. Instead, we referenced the function object which caused the default method to be called. The default method on

a function is the toString() function. The toString() function returns the contents of the object. The function is accessed as a data type and not executed because of the absence of the (). Without the () you are referencing the data type itself, with the parenthesis you execute the function. Therefore, to execute the functionDemo you would call it as follows: functionDemo().

This highlights a very common bug that can cause you to spend countless hours debugging unless you understand the distinction between executing functions and accessing them. If you accidentally omit the () to execute the function you will often get no visible script error other than your application does not run as expected.

By treating the function as an object JavaScript becomes much more powerful as you can assign and manipulate it just as you manipulate other variables. When you treat functions as variables you are manipulating function pointers. For example, you can assign a pointer to our new functionDemo to another variable the same as you assign any other variable:

// Assign a reference to the function
referenceFunctionDemo = functionDemo

// Executes the function

// Assign return value of the executed function.
saveResultOfFunction = functionDemo()

This is a part of a article from Scott Isaacs.
To know more click here...

No comments: