Details of JS function overloading

  • 2020-03-30 04:30:14
  • 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]);
//The function is called
add(10, 20);

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  String  Number  Object  Function  Boolean  Object  The object
Constructor  String  Number  Object  Function  Boolean  Array  User Define

<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: if(arguments[I] instanceof Number)
        //If (typeof(arguments[I])=="number")
        sum += arguments[i];
    return sum;
//The function is called

Related articles: