|
||
| Inside Technique : Extending JavaScript with Function Pointers : What is a Function Pointer? 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.
Running the above code generates the following output:
string
This is a string
function
function anonymous() { alert("I am a function!"); }
In this example we did not execute the 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 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:
The most common use of function pointers is for creating your own custom objects. Next we give you a brief introduction to creating objects with your own custom methods. Page 1:Extending JavaScript with Function Pointers © 1997-2000 InsideDHTML.com, LLC. All rights reserved. |