Home > Web Front-end > JS Tutorial > body text

Disguising method overloading through arguments parameters in javascript_javascript tips

WBOY
Release: 2016-05-16 16:34:41
Original
1438 people have browsed it

In many high-level object-oriented languages, there are method overloading. And javascript has no concept of method overloading. But we can use the arguments parameter to disguise it as an overload of the function

Let’s take a look at the code before simulating:

Copy code The code is as follows:

//Functions that do not declare formal parameters on the surface
function fun() {
alert("Sample code");
}
fun("Xiao Ming", 100, true);//I wrote three actual parameters

From the results, we see that even if we do not define formal parameters when declaring the function, we can still write actual parameters when calling the method. (Actually, formal parameters are written for programmers to see when calling functions)

Can we get the actual parameters in the code? The answer is yes: please see the code:

Copy code The code is as follows:

//Functions that do not declare formal parameters on the surface
function fun() {
alert(arguments[0]);//Get the value of the first actual parameter.
alert(arguments[1]);//Get the value of the second actual parameter.
alert(arguments[2]);//Get the value of the third actual parameter.
alert(arguments.length);//Get the actual number of parameters.
alert("Sample code");
}
fun("Xiao Ming", 100, true);//I wrote three actual parameters

Through the code, we can know that arguments (internal properties) itself is an array, and its function is to store the actual parameters of the method.

With the above knowledge points, you will have ideas for overloading simulation methods. We can make a judgment based on the number of actual parameters to execute different logic codes. The simple code is as follows:

Copy code The code is as follows:

function fun() {
if (arguments.length == 0) {
alert("Execute code without actual parameters");
}
else if(arguments.length==1)
{
alert("Execute the code passed in an actual parameter");
}
else if(arguments.length==2)
{
alert("Execute the code passed in two actual parameters");
}
}
fun();
fun("Xiao Ming");
fun("Xiao Ming", "Xiao Hua");
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