How to implement method overloading in js object oriented programming

  • 2020-03-30 03:31:04
  • OfStack

How do you implement method overloading in js? There are three issues involved

1. The call of the function of the same name

2. Special arguments in the function

3. How do I override methods with arguments

1. The call of the function with the same name

All know that in js if there are more than one function with the same name, then call the actual use of the last one every time, js is actually not overloaded, that is to say, if you define more than one function with the same name, single parameter is not the same, in the call, js regardless of the number of parameters, just before and after the order

Such as:


function test1(arg1) 
{ 
alert(" parameter 1 : "+arg1); 
} 
function test1(arg1,arg2,arg3) 
{ 
alert(" parameter 1 : "+arg1+" parameter 2 : "+arg2+" parameter 3 : "+arg3); 

} 
//The test code
function test(){ 
test1("1") 
}

  Although we called test1("1") and passed an argument, we actually called test1(arg1,arg2,arg3) and didn't call a method with only one argument because we passed an argument.

2. Special 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); 
} 
//The test code
function test(){ 
test1("1" . "2") 
}

We know that test1(arg1) is always called, that is, a function with only one argument, but how do we get the other arguments passed?

This requires a special argument in the function called arguments, which contains all arguments passed to the function


function test1() 
{ 
var text=""; 
for(var i=0;i<arguments.length;i++){ 
text+=" parameter "+i+":"+arguments[i]; 
} 
alert(text); 
} 
//The test code
function test(){ 
test1("1"); 
test1("1" . "2"); 
test1("1" . "2","3"); 
}

Tests show that arguments contain all the arguments passed to the function, and arguments. Length is different depending on the number of arguments actually passed. Arguments. Length represents the number of arguments actually passed to the function.

3. How to overload functions in js?

After the above tests, it is found that js can not directly achieve the function of the overload, but there is no way to achieve the method similar to the overload effect?

Yes, mainly using arguments

Such as:


function test1() 
{ 
var text=""; 
if(arguments.length==1) 
{ 
//Calls a method with a parameter
} 
else if(arguments.length==2) 
{ 
//Invokes a method with two arguments
} 
else { //Other methods
} 
}

Related articles: