当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js 函数重载

js 函数重载

2018年08月15日  | 移动技术网IT编程  | 我要评论

简单定义:根据不同参数长度来实现让同一个函数,进行不同处理。

function addMethod (obj, name, fun) {
    let old = obj[name]
    obj[name] = function () {
        if (fun.length === arguments.length) {
            return fun.apply(this, arguments)
        } else if (typeof old === 'function') {
            return old.apply(this, arguments)
        }
    }
}

使用:

var a = {}
addMethod(a, 'test', function(x){console.log(x)})
addMethod(a, 'test', function(x, y){console.log(x+y)})
addMethod(a, 'test', function(x, y, z){console.log(x+y+z)})
// test 是function名字,当参数长度不一样时候,执行的test不一样

测试:

a.test('s')
> s
a.test(1)
> 1
a.test(1,2)
> 3
a.test('1','2')
> 12
a.test('1','2','3')
> 123
a.test(1,2,3)
> 6

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网