函数重载必须依赖两件事情:判断传入参数数量的能力和判断传入参数的参数类型的能力
1.判断传入参数数量的能力
js判断传入参数数量可以用arguments.length这个属性来判断;
JavaScript代码
- function sendMsg(msg,obj){
- if(arguments.length==2)//判断参数的个数;
- obj.handleMsg(msg);
- else
- alert(msg);
- }
- sendMsg(“this site is http://www.css88.com”);
- sendMsg(“what is your site?”,{
- handleMsg : function(msg){
- alert(“My question is:”+“\”"+msg+“\”");
- }
- });
2.判断传入参数类型的能力
js判断传入参数类型的方有2种:typeof和constructor;
1.typeof
关于typeof的介绍可以查看:http://www.css88.com/article.asp?id=467
下面我们使用type0f来判断对类型的一个例子:
JavaScript代码
var num=“123″;
var arr=“1,2,3,4″;
if(typeof num==“string”)
num = parseInt(num);
alert(typeof num);
if(typeof arr==“string”)
arr = arr.split(“,”);
alert(arr.length);
2.constructor
查看例子:
JavaScript代码
var num=“123″;
var arr=“1,2,3,4″;
if(num.constructor==String)
num = parseInt(num);
alert(typeof num);
if(arr.constructor==String)
arr = arr.split(“,”);
alert(arr.length);
转自《JS函数重载和类型检查》