JavaScript cannot support function overloading, as follows:
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:
This way , you can pass in one parameter or two parameters to the function f(), such as f(10) and f(10,10);
Personally, although this can achieve overloading, it is also It is not very useful. We can implement overloading in a function according to the specific situation. If the two functions to be overloaded are very different, then keep the two functions. If the implementation of the two functions is basically the same, then you can Make judgments and process different parts in one function, instead of writing three functions as above, as follows:
Statement: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