ECMAScript arguments Object
- Previous Page Function Overview
- Next Page Function Object
The arguments object
In the function code, developers use a special object called argumentsIt is not necessary to explicitly state the parameter name, you can access them.
For example, in the function sayHi(), the first parameter is message. The value of this parameter can also be accessed using arguments[0], which is the value of the first parameter (the first parameter is located at position 0, the second parameter at position 1, and so on).
Therefore, it is not necessary to explicitly name the parameters to rewrite the function:
function sayHi() { if (arguments[0] == "bye") { return; } alert(arguments[0]); }
Detect Parameter Count
You can also use the arguments object to detect the number of parameters of the function, by referencing the property arguments.length.
The following code will output the number of parameters used each time the function is called:
function howManyArgs() { alert(arguments.length); } howManyArgs("string", 45); howManyArgs(); howManyArgs(12);
The above code will display "2", "0", and "1" in turn.
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 in the function. Any function defined by the developer can accept any number of parameters (according to Netscape's documentation, up to 255), without causing any errors. Any missing parameters will be passed to the function as undefined, and any extra parameters will be ignored.
Simulate Function Overloading
Use the arguments object to determine the number of parameters passed to the function, and you can 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); // Outputs "15" doAdd(40, 20); // Outputs "60"
When there is only one parameter, the doAdd() function adds 5 to the parameter. If there are two parameters, it will add the two parameters together and return their sum. Therefore, doAdd(10) outputs "15", and doAdd(40, 20) outputs "60".
Although not as good as overloading, it is enough to avoid this kind of restriction in ECMAScript.
- Previous Page Function Overview
- Next Page Function Object