简单定义:根据不同参数长度来实现让同一个函数,进行不同处理。
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