js 方法重载实现

function createFunOverLoad() {
  const funMap = new Map()
  console.log(funMap)
  const funOverLoad = function (...args) {
    const key = args.map(param => typeof param).join('-')
    console.log(key)
    const fn = funMap.get(key)
    if (fn) {
      return fn.apply(this, args)
    }
    return new Error('not match function')
  }
  funOverLoad.addFunImpl = function (...args) {
    const fun = args.pop()
    if (!fun || typeof fun !== 'function') {
      return
    }
    const paramKeys = args.join('-')
    funMap.set(paramKeys, fun)
  }
  return funOverLoad
}

const getUser = createFunOverLoad()
getUser.addFunImpl(() => console.log('no params'))
getUser()

getUser.addFunImpl('string', 'number', (name, age) => console.log('no params111111' + name + age))
getUser('aaaa', 12)

 

posted @ 2024-07-26 15:47  howhy  阅读(3)  评论(0编辑  收藏  举报