Javascript Object-oriented overload _js object-oriented

Source: Internet
Author: User
Tags getdate
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.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.