How to implement method overloading in JS? This involves three questions
1 invocation of a function with the same name
2 Special parameter arguments in the function
3 How to implement method overloading with arguments
1 Invocation of a function with the same name
All know in JS if there are more than one function with the same name, then the call actually only use the last one each time, JS is not overloaded, that is, if you define multiple functions with the same name, the single parameter is different, in the call, JS regardless of the number of parameters, just the order
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"), we pass a parameter, but the actual call is Test1 (ARG1,ARG2,ARG3), and there is no way to invoke only one argument because we passed a 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 the Code function test () { test1 ("1", "2") }
We know that the call is always test1 (ARG1), which is a function with only one argument, but how do you get the other arguments passed?
This is going to use a special parameter in the function arguments,arguments contains all the arguments 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");
After testing, arguments contains all the parameters passed to the function, and arguments.length differs depending on the number of actual arguments passed, Arguments.length represents the number of actual arguments passed to the function.
3 How can I implement overloading of functions in JS?
After the above test found that in JS can not directly implement the function of overloading, but there is no way to achieve similar overloaded effect method?
Yes, mostly using arguments.
For example:
function Test1 () { var text= ""; if (arguments.length==1) { //call method of a parameter } else if (arguments.length==2) { //method calling two arguments } Else { //other Methods } }