Implement function overloading and parameter default values in JavaScript

original
2012/08/10 09:24
Reading number 878

Parameter default value means that when calling a function, if an actual parameter is omitted, the function will automatically assign a default value to the parameter, which greatly improves the convenience and flexibility of function calling.

For example, in PHP, the string intercepting function substr (string, start, length) will intercept the string from the start position to the end of the string by default when the length is not specified. If the length is specified, the string with length starting from the start position will be intercepted. So if the substr (' http://www.hualai.net.cn ', 11,6), then hualai is returned; If the last parameter is omitted, substr (' http://www.hualai.net.cn ', 11), then return to hualai.net.cn.

For another example, in the jQuery framework, the $(selector). html () method is to get the HTML code in the element, while $(selector). html (content) is to set the HTML in the element. As we know, in C language, we can set default values for function parameters in the following forms:

 void foo(int a,  int b = 1, bool c = false);

In Java, you can set the default values of function parameters through function overloading:

 public void foo(int a){   foo(a, 1);   }   public void foo(int a, int b){   foo(a, b, false);   }   public void foo(int a, int b, bool c){   //Function content }

In JavaScript, how to set the default values of function parameters like jQuery? There is no way to assign values directly after parameters when defining functions in JavaScript like in C language, and there is no way to overload functions like in Java, but we can achieve this through a read-only array of arguments variables in JavaScript methods, as follows:

 function foo(){   var a = arguments[0] ?  arguments[0] : 1;   var b = arguments[1] ?  arguments[1] : false;   //Function content }

The above is to judge whether the parameter exists. If it does not exist, the default value will be attached to the variable. We can realize overloading by judging the type of the parameter:

 function foo(){   if(typeof arguments[0] == 'string')    Alert ('parameter type is string '); else if(typeof arguments[0] == 'number')    Alert ('parameter type is numeric '); }

Or:

 function foo(){   if(arguments[0].constructor == String)    Alert ('parameter type is string '); else if(arguments[0].constructor == Number)    Alert ('parameter type is numeric '); }

Expand to read the full text
Loading
Click to lead the topic 📣 Post and join the discussion 🔥
Reward
zero comment
eight Collection
four fabulous
 Back to top
Top