javascript這種語(yǔ)言是不支持方法的overload的,這意味著你沒(méi)辦法這樣描述一樣動(dòng)作:“吃東西”,你只能寫(xiě):“以吃大餐的方式吃東西”,“以吃點(diǎn)心的方式吃東西”。。。實(shí)在是挺惡心的。如果給你的方法取名已經(jīng)讓你感到山窮水盡時(shí),那只好用個(gè)小方法來(lái)解決,就是用參數(shù)的個(gè)數(shù)(或類(lèi)型)來(lái)在一個(gè)方法里面寫(xiě)if(){}else{}.....(挺丑陋的,不然還有什么好辦法?)
例:
function TestClass(){}
TestClass.prototype.eat = function(){
?? var len = arguments.length;
?? if(len == 1 )
????? alert('吃大餐');
? else if(len == 2)
????? alert('吃點(diǎn)心');
}
TestClass.prototype.ride= function(){
? var args = arguments;
?? if(typeof args[0] == 'string')
????? alert('騎自行車(chē)');
? else if(typeof args[0] == 'number')
????? alert('開(kāi)小車(chē)');
}
var tc = new TestClass();
tc.eat ('a');?
tc.eat ('a', 'b');?
tc.ride('bike');
tc.ride(1000);