JS中的函数重载 实参 形参 arguments

在Java中,方法可以进行重载

function add(int a,int b){
    //代码块
}
function add(int a,int b,int c){
    //代码块
}

调用的时候,会根据传入参数的不同,自动调用不同的方法。

那么在JS中呢?

如果在js中存在一个方法kid(p1,p2,p3),在别处进行调用的时候,少传了一个参数p3,会是什么结果呢?

function kid(p1,p2,p3){
    console.info(p1);
    console.info(p2);
    console.info(p3);
}


kid("This is the first parameter","This is the second parameter","This is the third parameter");
console.info("==============");
kid("This is the first parameter","This is the second parameter");

结果如下:


This is the first parameter         test.js:4 
This is the second parameter        test.js:5 
This is the third parameter         test.js:6 
==============                      test.js:11 
This is the first parameter         test.js:4 
This is the second parameter        test.js:5 
undefined                           test.js:6 

在最后一个参数处,直接打印除了undefined,并且没有报错。

那么如果出现3个名字一样,参数不一样的方法呢?

function kid(p1,p2,p3){
    console.info("this is parameter[3] method");
    console.info(p1);
    console.info(p2);
    console.info(p3);
}
function kid(p1){
    console.info("this is parameter[1] method");
    console.info(p1);
}
function kid(p1,p2,p3,p4){
    console.info("this is parameter[4] method");
    console.info(p1);
    console.info(p2);
    console.info(p3);
    console.info(p4);	
}

kid("This is the first parameter","This is the second parameter","This is the third parameter");
console.info("==============");
kid("This is the first parameter","This is the second parameter");

 

结果如下:

this is parameter[4] method   test.js:14
This is the first parameter   test.js:15
This is the second parameter  test.js:16
This is the third parameter   test.js:17
u
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值