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

How to implement overloading of JS functions_javascript skills

WBOY
Release: 2016-05-16 19:25:46
Original
1088 people have browsed it

JavaScript cannot support function overloading, as follows:

Copy code The code is as follows:

< script language="JavaScript">
function f(length)
{
alert("Height is:" length);
}

function f(length,width)
{
alert("Height is: " length ", width is: " width);
}


The above code is actually It won't work, because the number of parameters when the function is defined has nothing to do with the number of parameters when the function is called. In the function, you can use f.arguments[0] and f.arguments[1] to get the first and second parameters passed in when calling, so defining function(length), there is no need to call it later with f(10,10) problematic. So in the above code, the second function can never be called. So, how can we achieve functions like function overloading?
That is to use f.arguments.length in the function definition to determine the number of parameters passed in when calling. Then use different approaches to different situations.
As follows:
Copy code The code is as follows:

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template