函數重載必須依賴兩件事情:判斷傳入參數數量的能力和判斷傳入參數的參數類型的能力css
1.判斷傳入參數數量的能力
js判斷傳入參數數量能夠用arguments.length這個屬性來判斷;html
2.判斷傳入參數類型的能力
函數
js判斷傳入參數類型的方有2種:typeof和constructor;this
1.typeof
關於typeof的介紹能夠查看:http://www.css88.com/article.asp?id=467
下面咱們使用type0f來判斷對類型的一個例子:
spa
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
查看例子:
code
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);