FlyPig

if{}else if{}生活只有一个分支
posts - 11, comments - 9, trackbacks - 0, articles - 4
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

arguments的使用

Posted on 2006-11-21 21:43 FlyPig Lin 阅读(282) 评论(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);


只有注册用户登录后才能发表评论。


网站导航: