Javascript in arguments with overload introduction
- 2020-05-16 06:19:44
- OfStack
Because of a design error in the language, arguments can be treated as an array.
function zero () {
console.log(arguments[0]);
}
There will be
function zero () {
for(var i=0;i<arguments.length;i++){
console.log(arguments[i]);
}
}
It makes use of one fact of Javascript, Javasc
The arguments variable here provides an arrow-like interface to the argument. Because of the variable parameters of arguments here, we can use this interesting thing to do something interesting, like overloading.
Javscript overloading
There is a question about overloading on stackvoerflow, so you have the first answer
if (typeof friend === "undefined") {
} else {
}
And one answer is
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 just not a nice way to do it. Is our function going to end up looking like this?
function zero1 (){
console.log('arguments 1')
};
function zero2 (){
console.log('arguments 2')
};
function zero () {
if(arguments.length == 1){
zero1();
} else{
zero2();
}
}
It really doesn't look good at 1, even if we change it to switch.. case, that's not good either.
Javascript arguments is not an array
arguments is not an array as we saw 1 is an array, sometimes it might not be.
function hello(){
console.log(typeof arguments);
}
Here arguments is of type 1 object, although the array is also of type 1 object, although we can convert it to an array
var args = Array.prototype.slice.call(arguments);
But this also shows that this is not an array, it has only 11 properties of Array, length. And there were
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.