The Ecamscript function does not mind passing in the number of arguments, nor does it mind the type of arguments passed, even if the defined function accepts only two parameters, when the function is called without passing arguments, or even passing three arguments, etc., it doesn't matter. This is because in ecamscript the arguments are internally represented by an array, and the function is always accepted as an array. This parameter array can be accessed by the arguments object in the body of the function to get the value of each parameter passed. Arguments[0] can be used to access the first parameter passed when the function is called, and so on ... The following two functions function1 and function2 are actually equivalent to achieve the same effect. Note: In practice do not define two functions of the same name in a page, the following function will overwrite the previous function. There are no overloads in ecamscript similar to those in Java.
1 // 2 function Sayhi (name, message) { 3 alert ("Name:" + name + "message:" + message); 4 } 6 // function2 7 function Sayhi () { 8 alert (" Name: "+ arguments[0] + "Message:" + arguments[1 9 }
The above example shows that the parameters defined in the function are simply a convenience, not a necessity. You can get the number of arguments passed when the function was called by accessing the lenght property of arguments.
One of the more interesting things is that arguments always synchronizes with the corresponding named parameters of the function. When we use the arguments object to modify the value of the parameter, the following arguments[1] changes the value of the second parameter passed in, and num2 changes at the same time, but they do not access the same memory space, their memory space is independent, but the value is kept in sync.
1 function Doadd (NUM1, num2) {2 arguments[1] = ten; 3 return arguments[0] + num2; 4 }
If the above function executes Doadd (10), the first parameter will be assigned a value of 10, and the second parameter will be assigned a value of undefined.
In addition,all parameters in Ecamscript are passed as values, it is not possible to pass arguments by reference, as in Java.
Gain insight into the parameters of JavaScript functions