JS 实现函数重载
作者:xie392地址:https://v.douyin.com/ie9cwAE4/更新时间:2024-12-21
案例代码
1/**2* 创建函数重载3* @param {...any} args 参数4* @returns5*/6function createOverload(...args) {7const callMap = new Map()89function overload(...args) {10const key = args.map(arg=> typeof arg).join(',')11const fn = callMap.get(key)1213if(fn) {14return fn.apply(this, args)15}16throw new TypeError('fn not found')17}1819overload.addImpl = function(...args) {20const fn = args.pop()21if(typeof fn !== 'function') {22throw new TypeError('fn must be a function')23}24callMap.set(args.join(','), fn)25}2627return overload28}2930/**31* Tests32*33*/34function test(index) {35console.log('index:',index)36}3738const testOverload = createOverload()3940testOverload.addImpl('number',test)41testOverload.addImpl('string',(name)=>{42console.log("name:",name);43})44testOverload.addImpl('string','string',(name,sex)=>{45console.log("name:",name,"sex:",sex);46})4748testOverload(10)49testOverload('老六')50testOverload('张三','男')
输出结果:
1index: 102name: 老六3name: 张三 sex: 男
目录