How to implement method overloading in js? Three problems are involved.
1. Call of functions with the same name
2. Special parameter arguments in the function
3. How to use arguments to implement method Overloading
1. Call of functions with the same name
We all know that if multiple functions with the same name exist in js, only the last one is actually used for each call. js is not overloaded, that is, if multiple functions with the same name are defined, the single parameter is different. During the call, js only follows the order regardless of the number of parameters.
For example:
Function test1 (arg1) {alert ("parameter 1:" + arg1);} function test1 (arg1, arg2, arg3) {alert ("parameter 1: "+ arg1 +" parameter 2: "+ arg2 +" parameter 3: "+ arg3);} // test code function test () {test1 (" 1 ")}
Although we call test1 ("1") and pass a parameter, the actual call is test1 (arg1, arg2, arg3, the method that calls only one parameter.
2. Special parameter arguments in the function
If we use the following code:
Function test1 (arg1, arg2, arg3) {alert ("parameter 1:" + arg1 + "parameter 2:" + arg2 + "parameter 3:" + arg3 );} function test1 (arg1) {alert ("parameter 1:" + arg1);} // test code function test () {test1 ("1", "2 ")}
We know that test1 (arg1) is always called, that is, a function with only one parameter. But how can we get other passed parameters?
This requires the special parameter arguments in the function. arguments contains all parameters passed to the function.
Function test1 () {var text = ""; for (var I = 0; I <arguments. length; I ++) {text + = "parameter" + I + ":" + arguments [I];} alert (text) ;}// test the code function test () {test1 ("1"); test1 ("1", "2"); test1 ("1", "2", "3 ");}
Tests show that arguments contains all parameters passed to the function, and arguments. length varies according to the number of actually passed parameters, arguments. length indicates the number of actually passed function parameters.
3. How to Implement function overloading in js?
After the above tests, we found that function overloading cannot be implemented directly in js, but is there a way to achieve a similar Overload effect?
Yes, mainly because arguments
For example:
Function test1 () {var text = ""; if (arguments. length = 1) {// call a parameter method} else if (arguments. length = 2) {// call two parameter Methods} else {// other methods }}