How to implement method overloading in js? This involves three issues
1. The problem of calling functions of the same name
2. Special parameters in the function
3. How to use arguments to implement method overloading
1. The problem of calling functions of the same name
Everyone knows that if there are multiple functions with the same name in js, the last one will be used every time when calling. JS is actually not overloaded. That is to say, if multiple functions with the same name are defined, the single parameter is different. When calling, js does not care about the number of parameters, but only the order before and after
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"), passing a parameter, the actual call is test1(arg1, arg2, arg3), and we do not call a method with only one parameter because we pass a parameter.
2. Special parameters 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 the call is always test1(arg1), which means a function with only one parameter, but how to get other parameters passed?
This requires the use of special parameters in the function arguments, which contain all parameters passed to the function
function test1() { var text=""; for(var i=0;i<arguments.length;i++){ text+="parameters"+i+":"+arguments[i]; } alert(text); } //Test code function test(){ test1("1"); test1("1","2"); test1("1","2","3"); }After testing, it was found that arguments contain all parameters passed to the function, and arguments.length varies according to the number of actual parameters passed, and arguments.length represents the number of actually passed to the function parameters.
3. How to implement overloading of functions in js?
After the above tests, it was found that overloading of functions cannot be directly implemented in js, but is there a way to achieve similar overloading effects?
Yes, mainly use arguments
For example:
function test1() { var text=""; if(arguments.length==1) { //Calling a method of one parameter} else if(arguments.length==2) { //Calling a method of two parameters} else { //Other methods} }