Posted on 2006-11-21 21:43
FlyPig Lin 閱讀(297)
評論(0) 編輯 收藏
javascript這種語言是不支持方法的overload的,這意味著你沒辦法這樣描述一樣動作:“吃東西”,你只能寫:“以吃大餐的方式吃東西”,“以吃點心的方式吃東西”。。。實在是挺惡心的。如果給你的方法取名已經讓你感到山窮水盡時,那只好用個小方法來解決,就是用參數的個數(或類型)來在一個方法里面寫if(){}else{}.....(挺丑陋的,不然還有什么好辦法?)
例:
function TestClass(){}
TestClass.prototype.eat = function(){
?? var len = arguments.length;
?? if(len == 1 )
????? alert('吃大餐');
? else if(len == 2)
????? alert('吃點心');
}
TestClass.prototype.ride= function(){
? var args = arguments;
?? if(typeof args[0] == 'string')
????? alert('騎自行車');
? else if(typeof args[0] == 'number')
????? alert('開小車');
}
var tc = new TestClass();
tc.eat ('a');?
tc.eat ('a', 'b');?
tc.ride('bike');
tc.ride(1000);