Home >Web Front-end >JS Tutorial >Solution to JS function overloading_javascript skills
In object-oriented programming, many languages support function overloading, which can perform different operations based on the different number and type of parameters passed by the function. However, JS does not support it and requires us to do some extra small actions.
There is an interesting variable called arguments in the function execution context of JS. It stores all the parameters passed when the function is executed in the form of an array, even if the function definition does not define so many formal parameters. Another special feature is that compared with the Array type, the arguments variable has and has only one length attribute. Array methods, such as push, pop, etc., do not have it. It is just a "pseudo array": it has the length attribute and stores The array can be accessed using the array accessor [], and is read-only and not writable.
1. Overloading for different numbers of parameters
It should be clear here, just use the length attribute of the arguments function to judge.
2. Overloading of different types of parameters
For a dynamically typed language like JS, the arbitrary nature of variable declarations dilutes the strict variable types in the minds of developers importance (PS: It is also based on the ECMA system, and AS has introduced the mandatory type of variable declaration). Many unexpected BUGs are actually caused by this automatic conversion of variable types. In fact, JS provides a very accurate method for us to strictly detect the type of variables. The more common ones are the typeof method and the constructor attribute.
1. typeof variable returns the variable type
Through the above test, you can see that null, Object, and Array return object types, and the following method can solve this problem.
2.Constructor attribute detects variable type
Every object in JS has a constructor attribute, which is used to reference the function that constructs this object. The variable type can be detected by judging this reference.
Through the above test, it is easy to distinguish Array and Object type variables. Let's do a test on the custom object to see what happens.
This shows that the constructor attribute is also applicable to custom objects.
After clarifying the application of the above two methods, let’s return to the simulation of JS function overloading. The following example is overloading based on parameter types.
Attached is a very clever function that strictly detects parameter types and numbers: