Javascript function overloading solution sharing

  • 2020-03-30 01:46:40
  • OfStack

There is always a way to simulate function overloading using special object arguments in JavaScript. Use it to determine the number or type of arguments passed in to distinguish overloads.

1. Overload according to the number of parameters

Js determines the number of arguments passed by using the argument. Length property.


<script type="text/javascript">
function add() {
    if (arguments.length == 1) {
        alert(arguments[0] + 10);
    }
    else if (arguments.length == 2) {
        alert(arguments[0] + arguments[1]);
    }
}
//A function call
add(10);
add(10, 20);
</script>

2. Overloading by parameter type

3 ways to determine the type of a variable:
1. Judge the variable type with typeof statement, and the typeof statement returns the string corresponding to the type.
2. Determine the variable type with instanceof statement, which returns true/false.
Determine the type of a variable with the constructor attribute, which returns the constructor reference used to construct the variable.
It can be seen that typeof does not accurately identify a specific type, so we use constructors to do this.

typeof The string number The object The function Boolean The object The object The constructor The String Number The Object The Function Boolean Array User Define


Related articles: