Sharing of javascript function overload Solutions
This article mainly introduces the javascript function overloading solution, and uses arguments, a special object in JavaScript, to simulate function overloading. It is used to determine the number or type of input parameters to distinguish between overload
The Function Definition of JS can specify the formal parameter name. In more or less, we will assume that js can support at least different methods with different parameter numbers, but unfortunately this is just an illusion, all js parameters are passed in arguments. this parameter is similar to an array. During function calling, all real parameters are stored in this data structure, the formal parameter we specify when defining a function is actually to define a quick access method for the data in this data structure. That is to say, all js Functions Support infinite parameters. When the data type is weak, there is no difference between JS functions except the name?
There are always some methods. We can use the special object arguments in JavaScript to simulate function overloading. It is used to determine the number or type of input parameters to distinguish between overload.
1. Overload based on the number of parameters
Js can use the arguments. length attribute to determine the number of incoming parameters;
The Code 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. Overload Based on Parameter type
Three methods to determine the variable type:
1. Use the typeof statement to determine the variable type. The typeof statement returns the string corresponding to the type.
2. Use the instanceof statement to determine the variable type. The instanceof statement returns true/false.
3. Use the constructor attribute to determine the variable type. This attribute returns a reference to the constructor used to construct the variable.
Comparison table: we can see that typeof cannot accurately judge the specific type, so we use constructor to judge.
Typeof string number object function boolean object
Constructor String Number Object Function Boolean Array User Define
The Code 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>