Let me define it as follows:
CopyCode The Code is as follows: function getdate (){.....}
Function getdate (date ){.....}
The next method will overwrite the previous one, although no error is reported.
But we can indeed implement overload. If you have used jquery, you will have a deep understanding, such as $ ("# BTN "). val () is the value of the button whose ID is "BTN", while $ ("# BTN "). val ("Click me") is to assign a value to the button with ID "BTN.
So how can JavaScript be implemented (accurately speaking, it should be called "simulation ?.
The answer is simple: arguments
Arguments is a built-in object in Javascript that contains the actual parameters passed by the caller, but it is not limited to the list of parameters defined in the function declaration, during the call, only the same Length attribute as the array exists.
Let's take it as an "array" for the time being. We chose different implementations based on the length of the array and Its element types, thus simulating overload.
For details, see the following example:
Copy code The Code is as follows: function getdate (){
If (arguments. Length = 0 ){
VaR date = new date (). tolocaledatestring ();
Return "You have not entered the parameter. Current Time:" + date;
}
If (arguments. Length = 1 ){
If (arguments [0]. constructor = Date ){
Return "the parameter you entered is of the date type, and the current time is:" + arguments [0]. todatestring ();
}
If (arguments [0]. constructor = string ){
Return "the parameter you entered is of the string type, and the current time is:" + arguments [0];
}
}
}
So we can call:
Getdate ()
Getdate (new date ())
Getdate ("Monday ")
In this way, JavaScript overload is implemented, but we find that this "Implementation" is too stubborn. If there are too many parameters, the code will be messy, if {...} is everywhere {...}. Therefore, I do not recommend using this overload in JavaScript.