Main Page

Function class

The function
doAdd()
adds 10 to a number only if there is one argument; if there are two arguments,
they are simply added together and returned. So
doAdd(10)
outputs
“20”
whereas
doAdd(30,20)
out-
puts
“50”
. It’s not quite as good as overloading, but it is a sufficient workaround for this ECMAScript
limitation.
The Function class
Perhaps the most interesting aspect of ECMAScript is that functions are actually full-fledged objects.
A
Function
class represents each and every function a developer defines. The syntax for creating a
function using the
Function
class directly is as follows:
var
function_name
= new Function(
argument1
,
argument2
,..,
argumentN
,
function_body
);
In this form, each of the function arguments is one parameter, with the final parameter being the func-
tion body (the code to execute). Each of these parameters must be a string. Remember this function?
function sayHi(sName, sMessage) {
alert(“Hello “ + sName + “,” + sMessage);
}
It can also be defined like this:
var sayHi = new Function(“sName”, “sMessage”, “alert(\”Hello \” + sName + \”, \” +
sMessage + \”);”);
Admittedly, this form is a little bit harder to write because of the nature of strings, but understand that
functions are just reference types and they always behave as if using the
Function
class explicitly cre-
ated for them. Remember this example?
function doAdd(iNum) {
alert(iNum + 100);
}
function doAdd(iNum) {
alert(iNum + 10);
}
doAdd(10); //outputs “20”
As you remember, the second function overrides the first, making
doAdd(10)
output
“20”
instead of
“110”
. This concept becomes a whole lot clearer if this block is rewritten as follows:
doAdd = new Function(“iNum”, “alert(iNum + 100)”);
doAdd = new Function(“iNum”, “alert(iNum + 10)”);
doAdd(10);
Looking at this code, it is clear that the value of
doAdd
has changed to point to a different object. Yes,
function names are just reference values pointing to a function object and behave just as other pointers
do. It is even possible to have two variables point to the same function:
63
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 63


JavaScript EditorFree JavaScript Editor     Ajax Editor


©

R7