The number of parameters is used in JavaScript to implement the overload function.
Using the number of parameters for overloading, the method that comes to mind is
Function overload () {switch (arguments. length) {case 0: console. log ("none of my friends"); break; case 1: console. log ("have a friend"); break; case 2: console. log ("Two Friends"); break; case 3: console. log ("three friends"); break; case 4: console. log ("four friends"); break; // and so on }}
This method can achieve heavy load, but such code is relatively long, sometimes a lot in actual development. So we can use the following method.
Window. onload = function () {var cat = {friends: ["mimi", "pp", "gg"]} addMethod (cat, "sayName", function (a, B) {console. log ("Two Friends") ;}) addMethod (cat, "sayName", function () {console. log ("none of my friends");}) addMethod (cat, "sayName", function (a) {console. log ("have a friend") ;}) addMethod (cat, "sayName", function (a, B, c) {console. log ("three friends");}) cat. sayName ("xiaoming", "nihao"); cat. sayName (); cat. sayName ("xiaoming"); cat. sayName ("xiaoming", "xiaohong");} // implements overloading by using arguments. function addMethod (object, name, fn) {var old = object [name]; object [name] = function () {if (fn. length = arguments. length) return fn. apply (this, arguments); else if (typeof old = 'function') return old. apply (this, arguments );}}
This technique uses the closure to store different parameters in the closure as references.
The actual addMethod function is called, as shown in figure
Why?
Because of the closure, the addMethod function calls the object [name] literal variable old, which makes the garbage collection mechanism not recycle old, so old will always exist in the memory and will not disappear. We use this feature to implement inheritance.
When executing the sayName command below, we will search for the corresponding parameters along the references stored above, and then find the corresponding function for execution.
There are still deficiencies in this method:
1. Reload only applies to different quantities of parameters, but does not distinguish between types, parameters, or other things.
2. This method has the overhead of function calling. Because closures are used, some memory is occupied. It is not suitable for high-performance applications.
Summary
The above section describes how to use the number of parameters in JavaScript to implement the overload function. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!