In object-oriented languages, overloading is an important feature, while JavaScript, a self-proclaimed object-oriented language, does not directly provide overload functions. I have discussed the JavaScript object-oriented namespace, javascript object-oriented JavaScript classes, and JavaScript object-oriented private and public members in the previous sections.
Let me define it as follows:
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:
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:
The Code is as follows:
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.