函数重载必须依赖两件事情:判断传入参数数量的能力和判断传入参数的参数类型的能力
1.判断传入参数数量的能力
js判断传入参数数量可以用arguments.length这个属性来判断;
?
JavaScript代码
- function?sendMsg(msg,obj){ ??
- ????if(arguments.length==2)//判断参数的个数;
- ????????obj.handleMsg(msg); ??
- ????else??
- ????????alert(msg); ??
- } ??
- sendMsg(“this?site?is?https://www.7psus5.com”); ??
- sendMsg(“what?is?your?site?”,{ ??
- ????handleMsg?:?function(msg){ ??
- ????????alert(“My?question?is:”+“\””+msg+“\””); ??
- ????} ??
- });??
?2.判断传入参数类型的能力
?
js判断传入参数类型的方有2种:typeof和constructor;
1.typeof
关于typeof的介绍可以查看:https://www.7psus5.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);??
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂