1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>js的方法重载</title>
6 <script type="text/javascript">
7 // JavaScript不存在方法重载
8 // 通过arguments数组来模拟方法重载的效果
9 function add() {
10 var length = arguments.length;
11 var result;
12 switch (length)
13 {
14 case 2:
15 result = arguments[0] + arguments[1];
16 break;
17 case 3:
18 result = arguments[0] + arguments[1] + arguments[2];
19 break;
20 default:
21 result = -1;
22 break;
23 }
24 return result;
25 }
26 alert(add(1,2)); // 3
27 alert(add(1,2,3)); // 6
28 alert(add(1,2,3,4));// -1
29 </script>
30 </head>
31 <body>
32
33 </body>
34 </html>