重载:根据传入的参数不同,动态决定调用那种方法

  1. <script>
  2. function a(num1){
  3. console.log(num1)
  4. }
  5. function a(num1,num2){
  6. console.log(num1+num2);
  7. }
  8. a(1+2); //3
  9. a(1); //NaN
  10. </script>
  11. js不支持重载,要想支持重载,可以使用arguments对象
  12. <script>
  13. function a() {
  14. if (arguments.length == 1) {
  15. console.log(arguments[0])
  16. } else if (arguments.length == 2) {
  17. console.log(arguments[0] + arguments[1])
  18. }
  19. }
  20. a(1, 2); //3
  21. a(1); //1;
  22. </script>