1 JS函数重载
1.1 arguments参数
const arr = [1, 2, 3, 4, 5];
Array.prototype.partify = function () {
const len = arguments.length;
switch (len) {
case 0: return this;
case 1: return `(${
arguments[0]})`;
case 2: return `${
arguments[0]}-${
arguments[1]}`;
}
};
console.log(arr.partify());
console.log(arr.partify(1))
console.log(arr.partify(1,2))
1.2 闭包+arguments参数
function add(obj, name, fn) {
const old = obj[name];
obj[name] = function () {
if (fn.length === arguments.length) {
return fn.apply(this, arguments)
} else if (typeof old === 'function') {
return old.apply(this, arguments)
}
}
}
const student = {
name: 'jane' }
add(student, 'getInfo', function () {
console.log(this.name)
})
add(student, 'getInfo', function (suffix) {
console.log(`${
this.name}-${
suffix}`)
})
add(student, 'getInfo', function (a, b) {
console.log(`${
this.name}-${
(a + b)}`)
})
student.getInfo()
student.getInfo('cloud')
student.getInfo(20, 40)
2 TS函数重载
type unionType = number | string;
class Action {
start(name: number, age: number): string;
start(name: string, age: string): string;
start(name: string, age: number): string;
start(name: number, age: string): string;
start(name: unionType, score: unionType) {
if (typeof name === 'string' || typeof score === 'string') {
return 'person:' + name + ':' + score;
}
}
}
const action = new Action();
action.start('jane', 5);
action.start(5, 'good');
action.start(1, 5);