Introduction to arguments and overloading in Javascript, javascriptarguments
Due to language design errors, arguments can be considered as an array.
Copy codeThe Code is as follows:
Function zero (){
Console. log (arguments [0]);
}
There will also be
Copy codeThe Code is as follows:
Function zero (){
For (var I = 0; I <arguments. length; I ++ ){
Console. log (arguments [I]);
}
}
It exploits the fact of Javascript, namely, Objective C.
The arguments variable provides an interface similar to an Array for Real parameters. Because the variable parameters of arguments here, we can use this interesting thing to do something interesting, such as overloading.
Javscript overload
Stackvoerflow has a question about overload, so it has the first answer.
Copy codeThe Code is as follows:
If (typeof friend = "undefined "){
} Else {
}
Another answer is:
Copy codeThe Code is as follows:
Switch (arguments. length ){
Case 0:
// Probably error
Break;
Case 1:
// Do something
Break;
Case 2:
Default: // Fall through to handle case of more parameters
// Do something else
Break;
}
It's really hard to see this method. Is our function going to be like this at the end?
Copy codeThe Code is as follows:
Function zero1 (){
Console. log ('arguments 1 ')
};
Function zero2 (){
Console. log ('arguments 2 ')
};
Function zero (){
If (arguments. length = 1 ){
Zero1 ();
} Else {
Zero2 ();
}
}
It's really hard to understand. Even if we change the switch... case, it's not nice.
Javascript arguments is not an array
Arguments is not always an array as we can see, and sometimes it may not.
Copy codeThe Code is as follows:
Function hello (){
Console. log (typeof arguments );
}
Here, the arguments type is an object, although the array type is also an object, although we can convert it into an array
Copy codeThe Code is as follows:
Var args = Array. prototype. slice. call (arguments );
However, this also indicates that this is not an Array. It only has the unique attribute of Array, that is, length. In addition
Arguments. callee
Reference to the currently executing function.
Arguments. caller
Reference to the function that invoked the currently executing function.
Arguments. length
Reference to the number of arguments passed to the function.