If I define it like this:
function getDate() {.....}
function getDate(date){.....}
Then the latter method will overwrite the previous one, although no error will be reported.
But we can indeed implement overloading. If you have used jQuery, you will have a deep understanding of it. For example, $("#btn").val() is to get the button with the id "btn" value, and $("#btn").val("Click Me") assigns a value to the button with the id "btn".
So how is JavaScript implemented (accurately speaking, it should be called "simulation")?
The answer is simple: arguments
arguments is a built-in object in JavaScript, which contains the actual parameters passed by the caller, but is not limited to the parameter list defined by the function declaration. When it is called, it is the same as an array. length attribute.
Let’s understand it as an “array” for the time being. We choose different implementations based on the length of the array and the type of its elements, thereby simulating overloading.
Please see the following example for details:
function getDate(){
if(arguments.length==0){
var date=new Date().toLocaleDateString();
return "You did not enter parameters, now time:" date;
}
if(arguments.length==1){
if(arguments[0].constructor ==Date){
return "The parameter you entered is of Date type, now The time is: " arguments[0].toDateString();
}
if(arguments[0].constructor ==String){
return "The parameter you entered is of type String, and now the time is: " arguments[0];
}
}
}
So we can call like this:
getDate()
getDate( new Date())
getDate("Monday")
This achieves JavaScript overloading, but we found that this "implementation" is too reluctant. If there are too many parameters, it will It will seem overwhelming, and the code will be messy, with if{...} everywhere. So I don't recommend using such overloading in JavaScript.