The JS function definition can specify the formal parameter name. More or less, we think that js can at least support method overloading with different parameters. Unfortunately, this is just an illusion. All parameters of js are passed in the past with arguments. , This parameter is similar to an array. When a function is called, all the actual parameters are stored in this data structure. The formal parameters we specify when defining the function are actually defined as a quick definition for the data in this data structure. Access method. In other words, all functions of js support infinite parameters, and the data type is a weak type, so there is really no method difference between JS functions except for names?
There are always ways, we can use special object arguments in JavaScript to simulate function overloading. Use it to determine the number or type of incoming parameters to distinguish overloading.
1. Reload according to the number of parameters
JS to determine the number of incoming parameters can be judged by the arguments.length attribute;
The code copy is as follows:
<script type="text/javascript">
function add() {
if (arguments.length == 1) {
alert(arguments[0] + 10);
}
else if (arguments.length == 2) {
alert(arguments[0] + arguments[1]);
}
}
//Function call
add(10);
add(10, 20);
</script>
2. Reload according to parameter type
There are 3 ways to judge variable types:
1. Use the typeof statement to judge the variable type, and the typeof statement returns the string corresponding to the type.
2. Use the instanceof statement to judge the variable type, and the instanceof statement returns true/false.
3. Use the constructor attribute to determine the variable type, which returns the constructor reference used to construct the variable.
Comparison table: It can be seen that using typeof cannot accurately determine the specific type, so we use constructor to make judgments.
typeof | string | number | object | function | boolean | object | object |
constructor | String | Number | Object | Function | Boolean | Array | User Define |
The code copy is as follows:
<script type="text/javascript">
function add()
{
if (arguments.length == 0) return 0;
var sum=0;
for(var i=0; i<arguments.length; i++){
if(arguments[i].constructor == Number){
//Or change to: if(arguments[i] instanceof Number)
//Or change to: if(typeof(arguments[i])=="number")
sum += arguments[i];
}
}
return sum;
}
//Function call
alert(add(10));
alert(add(10,20));
</script>