↑
Main Page
arguments object
The arguments object
Within a function’s code, a special object called
arguments
gives the developer access to the function’s
arguments without specifically naming them. For example, in the
sayHi()
function, the first argument
is given the name
message
. The same value can also be accessed by referencing
arguments[0]
, which
asks for the value of the first argument (the first argument is in position 0, the second is in position 1,
and so on.). Therefore, the function can be rewritten without naming the argument explicitly:
function sayHi() {
if (arguments[0] == “bye”) {
return;
}
alert(arguments[0]);
}
The
arguments
object can also be used to check the number of arguments passed into the function by
referencing the
arguments.length
property. The following example outputs the number of arguments
each time the function is called:
function howManyArgs() {
alert(arguments.length);
}
howManyArgs(“string”, 45); //outputs “2”
howManyArgs(); //outputs “0”
howManyArgs(12); //outputs “1”
This snippet shows alerts displaying
“2”
,
“0”
, and
“1”
(in that order). In this way, the
arguments
object
puts the responsibility on the developer to check the arguments that are passed into a function.
Unlike other programming languages, ECMAScript functions don’t validate the number of arguments
passed against the number of arguments defined by the function; any developer-defined function accepts
any number of arguments (up to 255, according to Netscape’s documentation) without causing an
error. Any missing arguments are passed in as
undefined
; any excess arguments are ignored.
By using the arguments object to determine the number of arguments passed into the function, it is pos-
sible to simulate the overloading of functions:
function doAdd() {
if(arguments.length == 1) {
alert(arguments[0] + 10);
} else if (arguments.length == 2) {
alert(arguments[0] + arguments[1]);
}
}
doAdd(10); //outputs “20”
doAdd(30, 20); //outputs “50”
62
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 62
Free JavaScript Editor
Ajax Editor
©
→