Home  >  Article  >  Web Front-end  >  Detailed explanation of JS function overloading_javascript skills

Detailed explanation of JS function overloading_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:29:111590browse

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;

Copy code The code is as follows:


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

Copy code The code is as follows:


Have you guys understood the method of overloading JavaScript functions? If you have any questions, please leave a message

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