JavaScript函数重载
2020-08-04 本文已影响0人
ZoranLee
JQuery常用方法
- $('.test')
- $('.test','td')
- $(['.test', 'td'])
函数重载
同名函数的形式参数、数据类型或数量不同
于是乎脑海中一堆if 和 else喷涌而出:
function overLoad() {//根据arguments类型和长度进行不同的处理
switch(arguments.length) {
case 0:
break;
case 1:
break;
case 2:
break;
...
}
}
借鉴jQuery 实现函数重载
function addMethods(obj, name, f) {
let old = obj[name];
obj[name] = function () {
if (f.length === arguments.length) {
return f.apply(this, arguments);
} else {
return old.apply(this, arguments);
}
}
}
let people = {
name: ['张三', '李四', '王五']
};
let find0 = function () {
return this.name;
};
let find1 = function (name) {
var arr = this.name;
for (let i = 0; i <= arr.length; i++) {
if (arr[i] === name) {
return i
}
}
};
addMethods(people, 'find', find0)
addMethods(people, 'find', find1)
console.log(people.find('李四'));
重载的优化
Object.prototype.addMethod = function (name, fn) {
var old = this[name];
this[name] = function () {
var fncLen = fn.length,
argLen = arguments.length;
if (fncLen === argLen) {
return fn.apply(this, arguments);
} else if (typeof old === "function") {
return old.apply(this, arguments);
} else {
throw new Error("no method with " + argLen + " param(s) defined!");
}
}
};
//函数多参数重载,添加方法和使用:
let find0 = function () {
return 'no param';
};
let find1 = function(param){
return param
}
let people = {};
people.addMethod('find', find0)
people.addMethod('find', find1)
console.log(people.find()); // no param
console.log(people.find('bb'));//bb
收工