Home  >  Article  >  Web Front-end  >  JavaScript function overloading solution sharing_Basic knowledge

JavaScript function overloading solution sharing_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:59:221075browse

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 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;

Copy code The code is as follows:


2.根据参数类型重载

Three ways 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 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 judge.

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

Copy code The code is as follows:



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn