JavaScript cannot support overloading of functions, as follows:
- function F(length )
- {
- Alert ("High is:"+length);
- }
- function F(length,width )
- {
- Alert ("High is:"+length+", Width:"+width );
- }
The above code does not work, because there is no relationship between the number of arguments in the function definition and the number of arguments in the function call. You can use F.arguments[0] and f.arguments[1 in the function to get the first and second arguments that are passed in when called, so it is no problem to define function (length), followed by the F (10,10) call. So in the above code, the second function is never going to be called, so how can you implement functions like function overloading?
That is to judge the number of arguments passed in the call with f.arguments.length in the function definition. Then different processing methods are used for different situations.
As follows:
- function F()
- {
- var Len = arguments. length ;
- if (1 = = len )
- {
- var length = arguments [0];
- var width = arguments [1];
- F2 (length,width);
- }
- Else
- {
- var length = arguments [0];
- F1 (length);
- }
- }
- function F1(length )
- {
- Alert ("High is:"+length);
- }
- function F2(length,width )
- {
- Alert ("High is:"+length+", Width:"+width );
- }
In this way, you can pass in a parameter to the function f () or pass in two parameters, such as f (10) and F (10,10);
Personally, although this can be implemented overload, but it is not very good, we can implement the overload in a function according to the situation, if the two functions to be overloaded with a large difference, then retain two functions, and if the implementation of two functions basically similar, then you can judge in a function, processing different parts, Instead of having to write three functions like the one above, the following:
- function F(length )
- {
- var Len = arguments. length ;
- if (1 = = len )
- {
- var width = arguments [1];
- Alert ("High is:"+length+", Width:"+width );
- }
- Else
- {
- Alert ("High is:"+length);
- }
- }