function overloading of JavaScript

Source: Internet
Author: User

The Java language in the overloading and rewriting of functions is very important concept, so in the writing JS sometimes think of this usage, rewrite first not to say, here only say overloaded.

function Test (one) {     alert ("above"function  Test (one,two) {     alert ("below  " </srcipt>

As in the code, the call will find that no matter you pass a few parameters, will only pop up "below", swap 2 functions of the upper and lower positions and then execute, you will find that will only pop up "above".

The conclusion is thatJS does not support overloading of functions, and the same name function only executes the one that was last defined :

But this is not to say that we cannot use overloading, can be replaced by some alternative means to achieve the effect of overloading. We know that there is a hidden parameter in the JS function arguments, which is an array of parameters that the receive function passes in. Therefore, we can implement function overloading in disguise by judging the number of parameters passed in by the function:

functionTest () {if(Arguments.length==1) {alert ("1"); }Else if(Arguments.length==2) {alert ("2"); }Else{                 return false; }}test (1); Output 1test (The); Output 2a=test (); alert (a); Output False

function overloading of 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.