---
title: "JS中使用arguments模拟重载"
author: "select*from爱"
date: "2010-06-22T14:01:25Z"
tags: []
categories: ["Web前端"]
slug: "js-arguments"
draft: false
lastmod: "2010-06-22T14:02:20Z"
id: 696402
url: "https://esayjava.iteye.com/blog/696402"
---

今天看读别人的代码的时候发现了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
```