arguments object
In function code, special object arguments are used, developers can access them without explicitly pointing out parameter names.
For example, in the function saysHi(), the first parameter is message. This value can also be accessed with arguments[0], that is, the value of the first parameter (the first parameter is at position 0, the second parameter is at position 1, and so on).
Therefore, you can override the function without explicitly naming the parameters:
function saysHi() {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 and refer to the attribute arguments.length.
The following code will output the number of parameters used for each call to the function:
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 that the number of parameters passed to a function is equal to the number of parameters defined by the function. Functions defined by developers can accept any number of parameters (according to Netscape's documentation, up to 255) without throwing any errors. Any missing parameters will be passed to the function as undefined, and the redundant functions will be ignored.
Simulate function overloading
Use the arguments object to determine the number of parameters passed to the function, and then 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 to return their sum. So, doAdd(10) outputs "15", while doAdd(40, 20) outputs "60".
Although not as good as overloading, it is enough to avoid this limitation of ECMAScript.