↑
Main Page
ECMAScript
var doAdd = new Function(“iNum”, “alert(iNum + 10) “);
var alsoDoAdd = doAdd;
doAdd(10); //outputs “20”
alsoDoAdd(10); //outputs “20”
Here, the variable
doAdd
is defined as a function, and then
alsoDoAdd
is declared to point to the same
function. Both can then be used to execute the function’s code and output the same result
, “20”
. So if a
function name is just a variable pointing to a function, is it possible to pass a function as an argument to
another function? Yes!
function callAnotherFunc(fnFunction, vArgument) {
fnFunction(vArgument);
}
var doAdd = new Function(“iNum”, “alert(iNum + 10)”);
callAnotherFunc(doAdd, 10); //outputs “20”
In this example,
callAnotherFunction()
accepts two arguments: a function to call and an argument
to pass to the function. This code passes the
doAdd()
function into
callAnotherFunction()
with an
argument of
10
, outputting
“20”
.
Because functions are reference types, they can also have properties and methods. The one property
defined in ECMAScript is
length
, which indicates the number of arguments that a function expects.
Example:
function doAdd(iNum) {
alert(iNum + 10);
}
function sayHi() {
alert(“Hi”);
}
alert(doAdd.length); //outputs “1”
alert(sayHi.length); //outputs “0”
The function
doAdd()
defines one argument to pass in, so its
length
is
1
;
sayHi()
defines no argu-
ments, so its length is
0
. Remember, ECMAScript functions can accept any number of arguments (up to
255) regardless of how many are defined. The
length
property just gives a convenient way to check
how many arguments are expected by default.
Function objects also have the standard
valueOf()
and
toString()
methods shared by all objects.
Both of these methods return the source code for the function and are particularly useful in debugging.
For example:
Even though it’s possible to create a function using the
Function
constructor, it’s
best to avoid it because it’s slower than defining the function in the traditional man-
ner. However, all functions are considered instances of
Function
.
64
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 64
Free JavaScript Editor
Ajax Editor
©
→