在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