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