Function overloading proficient in Javascript

Source: Internet
Author: User

Overloading is a common feature in object-oriented systems. Although JS does not directly support function overloading, function overloading can be implemented in many ways. Every function in JS carries a variable that only works within the range of this function. It is called the parameter argument. It is a dimension array containing all parameters passed to the function, it is not an array in the true sense. It cannot be modified, but can access its elements and attributes.

The following example provides an intuitive understanding:

<SCRIPT type = "text/JavaScript" Language = "JavaScript"> // function of sending a message: sendmessage (MSG, OBJ) {// If the input parameter is two, use OBJ to send the message if (arguments. length = 2) obj. handlemsg (MSG); // if no parameter is input, the error message else if (arguments. length = 0) Alert ("an error occured! "); // If the input parameter is MSG, the message else if (typeof (MSG) =" string ") Alert (MSG) is displayed; // If the input parameter is OBJ, use OBJ to send the message else if (typeof (MSG) = "object") MSG. handlemsg ();} sendmessage ("Hello, world! "); Sendmessage (" how are you? ", {Handlemsg: function (MSG) {alert (" this is a custom message: "+ MSG) ;}}); sendmessage ({handlemsg: function () {alert ("this is a custom message") ;}}); </SCRIPT>

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.