The function definition of JS can specify formal parameter names. More or less, we would think that js can at least support method overloading with different number of parameters. However, unfortunately this is just an illusion. All parameters of js are in arguments. Passed, this parameter is similar to an array. When the function is called, all actual parameters are stored in this data structure. The formal parameters specified when we define the function are actually defined for the data in this data structure. A quick way to access. In other words, all functions in JS support unlimited parameters, and the data type is a weak type. So there is really no method difference between JS functions except their names?
There is always a way. We can use the special object arguments in JavaScript to simulate function overloading. Use it to determine the number or type of parameters passed in to distinguish overloading.
1. Overload according to the number of parameters
js can use the arguments.length attribute to determine the number of incoming parameters;
2. Overloading according to parameter type
3 ways to determine 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 the constructor reference used to construct the variable.
Comparison table: It can be seen that typeof cannot accurately determine the specific type, so we use constructor to determine.
typeof string number object function boolean object object
constructor String Number Object Function Boolean Array User Define
Have you guys understood the method of overloading JavaScript functions? If you have any questions, please leave a message