js ts函数重载

1 JS函数重载

1.1 arguments参数

 const arr = [1, 2, 3, 4, 5]; //不能写成箭头函数,否则this指向window
        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()); //[1,2,3,4,5] 
        console.log(arr.partify(1)) //(1)
        console.log(arr.partify(1,2)) //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()  // jane
        student.getInfo('cloud') // jane-cloud
        student.getInfo(20, 40) // jane-60

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);//person:jane:5
action.start(5, 'good');//person:5:good
action.start(1, 5);//无输出

你可能感兴趣的:(javascript,javascript,前端,typescript)