If I were to define this:
Copy Code code as follows:
function GetDate () {...}
function GetDate (date) {...}
Then the latter method will overwrite the previous one, although no error.
But we can really overload it, if you've ever used jquery, you will have a deep understanding, such as $ ("#btn"). Val () is the value of the button that gets the id "BTN", and $ ("#btn"). Val ("Point Me") assigns a value to the button with the id "btn".
So how does JavaScript come about (exactly what should be called "impersonation")?
The answer is simple: arguments
Arguments is a built-in object in JavaScript that contains the actual arguments passed by the caller, but is not limited to the list of parameters defined by the function declaration, but it has a length attribute just as it does with the array.
Let's take it as an "array" to understand that we have chosen different implementations based on the length of the array and the type of its elements, thus simulating the overload.
Please see the following example:
Copy Code code as follows:
function GetDate () {
if (arguments.length==0) {
var date=new date (). toLocaleDateString ();
Return "You do not have input parameters, now time:" +date;
}
if (arguments.length==1) {
if (Arguments[0].constructor ==date) {
Return "The parameter you entered is the date type, now time is:" +arguments[0].todatestring ();
}
if (Arguments[0].constructor ==string) {
Return "The parameter you entered is of type string, now time is:" +arguments[0];
}
}
}
So we can call this:
GetDate ()
GetDate (New Date ())
GetDate ("Monday")
This realizes the JavaScript overload, but we found that such a "realization" is too reluctantly, if more parameters, it will appear powerless, the code will be very messy, everywhere is if{...}. So I don't recommend using such overloads in JavaScript.