arguments object
In function code, using the special object arguments, developers can access parameter names without explicitly naming them.
For example, in the function sayHi(), the first parameter is message. This value can also be accessed with arguments[0], which is the value of the first argument (the first argument is at position 0, the second argument is at position 1, and so on).
Thus, the function can be rewritten without explicitly naming the parameters:
function sayHi() { if (arguments[0] == "bye") { return; } alert(arguments[0]); }
Number of detection parameters
You can also use the arguments object to detect the number of parameters of the function, just reference the property arguments.length.
The following code will output the number of parameters used in each function call:
function howManyArgs() { alert(arguments.length); } howManyArgs("string", 45); howManyArgs(); howManyArgs(12);
The above code will display "2", "0" and "1" in sequence.
Note: Unlike other programming languages, ECMAScript does not verify whether the number of parameters passed to a function is equal to the number of parameters defined by the function. Developer-defined functions can accept any number of arguments (up to 255, according to Netscape's documentation) without raising any errors. Any missing arguments will be passed to the function as undefined, and extra functions will be ignored.
Simulate function overloading
Use the arguments object to determine the number of parameters passed to the function to simulate function overloading:
function doAdd() { if(arguments.length == 1) { alert(arguments[0] + 5); } else if(arguments.length == 2) { alert(arguments[0] + arguments[1]); } }
doAdd(10); //Output "15"
doAdd(40, 20); //Output "60"
When there is only one parameter, the doAdd() function adds 5 to the parameter. If there are two parameters, the two parameters are added and their sum is returned. So, doAdd(10) outputs "15", while doAdd(40, 20) outputs "60".
Although not as good as overloading, it is enough to get around this limitation of ECMAScript.