js 函数重载


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

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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM