Some concepts:
Overload (Overload):
What is: the same function name, a number of different parameter list functions, when called, according to the different parameters, automatically select the corresponding function call!
Why: Lighten the burden of the caller, a function name that can perform a variety of operations
When: a task, according to the different parameters, the implementation of different operating procedures
How to: JS syntax does not support overloading effects
WORKAROUND: Within all function objects, an automatically built-in
The following functions are implemented:
function Pay () { console.log ("Payment");} function Pay (num) { console.log ("cash payment");} function Pay (card,pwd) { console.log ("swipe paid");} The following are the ideal overloads to achieve the effect of pay () //"payment" paid (500)//"Cash paid" pay ("xxxxxxxxxxxxx", "546464")//Credit card payment// and due to The declaration advance feature in JavaScript will result in the actual output of the following result pay ()/ /Swipe Pay (500)//swipe to pay ("xxxxxxxxxxxxx", "546464")//Credit card payment
So we need arguments objects in JavaScript to simulate overloaded effects
Concept two:
Within all function objects, a arguments object is automatically built in
Arguments object:
Class Array object that specifically holds all parameter values passed in to the function
Class Array object: (object like array)
VS array: Same: subscript, length, for traversal
Different: Class array objects are object, not array, cannot use array's API
Array is an array type and can use all the API
The resulting solution is as follows:
function Pay () { if (arguments[0]==null) { console.log ("payment"); } else if (typeof (Arguments[0]) = = "Number") { console.log ("cash payment, receive you" +arguments[0]+ "Yuan"); } else{ console.log ("swipe payment, your card number" +arguments[0]+ "debit Success");} } Pay (); Paid pay (500);//cash payment, your 500 yuan pay ("14564645646");//Credit card payment, your card number 14564645646 debit Success
Of course, the use of arguments objects far more than this one, here is a simple introduction.
Using argument objects to implement overloading in JavaScript (overload)