How to implement method overloading in js? This involves three issues
1. Problem with calling function with the same name
2. Special parameters arguments in the function
3. How to use arguments to implement method overloading
1. Problem with calling function with the same name
We all know that if there are multiple functions with the same name in js, only the last one will be used each time. In fact, js is not overloaded. That is to say, if multiple functions with the same name are defined, a single The parameters are different. When calling, js does not care about the number of parameters, but only the order
For example:
function test1(arg1) { alert("参数1:"+arg1); } function test1(arg1,arg2,arg3) { alert("参数1:"+arg1+"参数2:"+arg2+"参数3:"+arg3); } //测试代码 function test(){ test1("1") }
Although we called test1("1") and passed one parameter, the actual call was test1(arg1, arg2, arg3). It was not because we passed one parameter and the call had only one parameter. method.
2. Special parameters in the function arguments
If we use the following code
function test1(arg1,arg2,arg3) { alert("参数1:"+arg1+"参数2:"+arg2+"参数3:"+arg3); } function test1(arg1) { alert("参数1:"+arg1); } //测试代码 function test(){ test1("1","2") }
We know that the call is always test1(arg1), which is a function with only one parameter, but how to get the other parameters passed?
This requires the use of special parameters 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+="参数"+i+":"+arguments[i]; } alert(text); } //测试代码 function test(){ test1("1"); test1("1","2"); test1("1","2","3"); }
After testing, it was found that arguments contains all parameters passed to the function, and arguments.length varies according to the actual number of parameters passed. arguments.length represents the actual number of parameters passed to the function.
3. How to implement function overloading in js?
After the above tests, we found that overloading of functions cannot be directly implemented in js, but is there any way to achieve a similar overloading effect?
Yes, the main thing is to use arguments
For example:
function test1() { var text=""; if(arguments.length==1) { //调用一个参数的方法 } else if(arguments.length==2) { //调用两个参数的方法 } else { //其他的方法 } }