In small projects for JavaScript use, just write a few function on the line. But in large projects, especially in the development of the pursuit of a good user experience of the site, such as SNS, will use a lot of javascrpt, sometimes JavaScript workload than C #, then write a bunch of function, it will appear very messy, disorganized, even a naming conflict, It's cumbersome to manage and maintain. In this case, we need to use object-oriented thinking to develop JavaScript. So let's just say:
Overloading is an important feature in object-oriented languages, and JavaScript, a self-proclaimed object-oriented language, does not provide the overloaded functionality directly.
If I define this:
function GetDate () {...}
function GetDate (date) {...}
Then the latter method will overwrite the previous one, although not an error.
But we can really overload it, and if you use jquery, you'll have a deep sense, like $ ("#btn"). Val () is the value of the button that gets the id "BTN", while $ ("#btn"). Val ("Point Me") assigns a value to the button with the id "btn".
So how does JavaScript come into being (accurately, it should be called "simulation")?
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 argument list defined by the function declaration, but only when it is called with the same length property as the array.
Let's just think of it as an "array", and we'll simulate overloading by selecting different implementations based on the length of the array and the type of its elements.
For details, see the following example:
function GetDate () {
if (arguments.length==0) {
var date=new date (). toLocaleDateString ();
Return "You have no input parameters, now time:" +date;
}
if (arguments.length==1) {
if (Arguments[0].constructor ==date) {
Return "The parameter you entered is the date type, and now the time is:" +arguments[0].todatestring ();
}
if (Arguments[0].constructor ==string) {
Return "The parameter you entered is of type string and the time is now:" +arguments[0 ";
}
}
}
So we can call it this way:
GetDate ()
GetDate (New Date ())
GetDate ("Monday")
This implements the JavaScript overload, but we found that the "implementation" is too reluctant, if the parameters are more, will appear to be powerless, the code will be very messy, everywhere is if{...}. So I don't recommend using such overloads in JavaScript.
Object-oriented JavaScript (4): Overloading