Home > Web Front-end > JS Tutorial > Introduction to arguments and overloading in Javascript_javascript skills

Introduction to arguments and overloading in Javascript_javascript skills

WBOY
Release: 2016-05-16 16:09:13
Original
1242 people have browsed it

Due to a language design error, arguments can be treated as an array.

Copy code The code is as follows:

function zero () {
console.log(arguments[0]);
}

There will also be
Copy code The code is as follows:

function zero () {
for(var i=0;i console.log(arguments[i]);
}
}

It takes advantage of the fact that Javascript is Javasc

The arguments variable here provides an array-like interface for actual parameters. Because of the variable parameters of arguments here, we can use this interesting thing to do some interesting things, such as overloading.

Javscript reload

There is a question about overloading on stackvoerflow, so I have the first answer

Copy code The code is as follows:

if (typeof friend === "undefined") {

} else {

}

Another answer is

Copy code The 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 just that this method really doesn’t look good. Is our function going to look like this in the end?

Copy code The 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 really doesn’t look good at all. Even if we change the switch..case, it won’t look good either.

Javascript arguments is not an array

arguments is not always an array as we see, sometimes it may not be.

Copy code The code is as follows:

function hello(){
console.log(typeof arguments);
}

The type of arguments here is an object, although the type of array is also an object, although we can convert it to an array
Copy code The code is as follows:

var args = Array.prototype.slice.call(arguments);

But this also shows that this is not an array. It only has the only attribute of Array, which 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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template