JS 实现函数重载

作者:xie392地址:https://v.douyin.com/ie9cwAE4/更新时间:2024-12-21

案例代码

1
/**
2
* 创建函数重载
3
* @param {...any} args 参数
4
* @returns
5
*/
6
function createOverload(...args) {
7
const callMap = new Map()
8
9
function overload(...args) {
10
const key = args.map(arg=> typeof arg).join(',')
11
const fn = callMap.get(key)
12
13
if(fn) {
14
return fn.apply(this, args)
15
}
16
throw new TypeError('fn not found')
17
}
18
19
overload.addImpl = function(...args) {
20
const fn = args.pop()
21
if(typeof fn !== 'function') {
22
throw new TypeError('fn must be a function')
23
}
24
callMap.set(args.join(','), fn)
25
}
26
27
return overload
28
}
29
30
/**
31
* Tests
32
*
33
*/
34
function test(index) {
35
console.log('index:',index)
36
}
37
38
const testOverload = createOverload()
39
40
testOverload.addImpl('number',test)
41
testOverload.addImpl('string',(name)=>{
42
console.log("name:",name);
43
})
44
testOverload.addImpl('string','string',(name,sex)=>{
45
console.log("name:",name,"sex:",sex);
46
})
47
48
testOverload(10)
49
testOverload('老六')
50
testOverload('张三','男')

输出结果:

1
index: 10
2
name: 老六
3
name: 张三 sex: 男