ITeye博客

JS中使用arguments模拟重载

select*from爱 · 2010-06-22 14:01 · js · Web前端 · Markdown

今天看读别人的代码的时候发现了arguments对象,不明白之下翻了下书,总结了下,以便备用

写给不会的朋友,会者飘过~

ECMASCript规范中不存在重载这个概念,测试代码 如下

function test(){
 }
function test(){
alert('1');
}
function test(){
alert('2');
}
test();//2

 根据顺序执行的规则,前2个test函数被最后一个test函数覆盖,所以最后输出为2

---使用arguments,可以无法指出参数名的情况下进行访问

----arguments可以看错为一个参数列表数组,通过argument[index]的形式对参数进行访问

-----arguments.length获得参数列表长度

function test(){
  if(arguments[0]!=undefined){
  alert(arguments[0]);
  }
}
test(2);//2

 根据 上面对arguments的介绍,结合argument.length.就可以实现方法的重载,虽然不是很方便,但却可以绕开ECMASCript不能重载的限制了

function test(){
  if(arguments.length==1){
  alert(arguments[0]);
  }
  else if(arguments.length==2){
  alert(arguments[0]+arguments[1]);
  }
}
test(2);//2
test(1,2);//3

评论(1)

  1. #1 楼 · butnet · 2010-06-22 15:05

    确实这样可以模拟重载的功能, 但一起里面还会加些typeof之类的判断, 在Ext里,有很多方法就是这样实现混合参数的。 用起来确实方便。

评论功能维护中,当前仅展示历史评论。