js实现函数重载的两种方式
1、利用函数体中的arguments对象实现
function fnOverload() {
switch (arguments.length) {
case 0:
console.log("no argument");
break;
case 1:
console.log("one argument");
break;
case 2:
console.log("two arguments");
break;
default:
console.log("more than two arguments");
break;
}
}
fnOverload(); // no argument
fnOverload(1); // one argument
fnOverload(1,2); // two arguments
fnOverload(1,2,3); // more than two arguments
fnOverload(1,3,4); // more than two arguments
</code></pre>
当参数为3个或3个以上时,都会打印输出'more than two arguments', 这就出现了可扩展性差的问题,如果需要增加3个或3个参数以上的方法,需要修改fnOverload方法中的代码。
2、利用闭包实现,虽然核心也是利用了函数体重的arguments对象实现,但可扩展性较强
function addMethod(object,name,fn) {
var old = object[name]; // 保存上次定义的name属性对应的值
object[name] = function() {
if(fn.length == arguments.length) { // fn.length保存此次定义时fn函数的参数个数
return fn.apply(this,arguments);
} else if(typeof old == "function"){
return old.apply(this,arguments);
}
}
}
var people = {
firstName : "kobe",lastName : "james"
};
addMethod(people,"find",function() {
return Object.keys( people );
});
addMethod(people,function(firstName) {
return people[firstName];
});
addMethod(people,function(firstName,lastName) {
return people[firstName] + people[lastName] + "";
});
console.log( people.find() ); // ["firstName","lastName","find"]
console.log( people.find("firstName") ); // kobe
console.log( people.find("firstName","lastName") ); // kobejames
</code></pre>