JS 中沒有函數(shù)重載,又是如何實(shí)現(xiàn)函數(shù)重載的呢?

一、什么是函數(shù)重載?
同名的多個(gè)函數(shù)。 不同的參數(shù)。
二、JS中有函數(shù)重載嗎?

我們?cè)?《JavaScript 高級(jí)程序設(shè)計(jì)(第三版)》 書中能看到,JS 中的同名函數(shù),前面的會(huì)被最后面的函數(shù)覆蓋掉,根本無(wú)法實(shí)現(xiàn)多種功能,如:
function add(a,b) {return a+b}function add(a, b, c) {return a + b + c}console.log(add(1,2)); // NaNconsole.log(add(1,2,3 ));// 6
如果我們需要使用 JS 實(shí)現(xiàn)上述 add 方法,將兩個(gè)或三個(gè)數(shù)值進(jìn)行求和,該怎么解決呢?
解決1:利用 arguments
function add() {var reg = arguments;if (reg.length == 2) {return reg[0] + reg[1]} else if(reg.length == 3) {return reg[0] + reg[1] + reg[2]}}console.log(add(1, 2)) //3console.log(add(1, 2, 3)) //6
上述方法雖然實(shí)現(xiàn)了上述簡(jiǎn)單功能,勉強(qiáng)能算得上是一種函數(shù)重載的實(shí)現(xiàn)方法,但是存在一定的弊端。
它的缺點(diǎn):
如果功能復(fù)雜時(shí),代碼量過大。
不利于維護(hù)和復(fù)用。
這時(shí)候問題來了,利用 JS 如何實(shí)現(xiàn)呢?可以通過閉包的形式可以簡(jiǎn)單地實(shí)現(xiàn)。
三、JS 如何實(shí)現(xiàn)重載?
function addMethodToObject (obj, name, fn) {const temp = obj[name]obj[name] = function () {if (fn.length === arguments.length) {return fn.apply(obj, arguments)} else if (typeof temp === 'function') {return temp.apply(obj, arguments)}}}
上述方法用來給一個(gè)對(duì)象添加自定義方法,能夠接收三個(gè)參數(shù):
需要添加方法的對(duì)象
自定義方法名
定義方法具體要實(shí)現(xiàn)的功能,通過回調(diào)實(shí)現(xiàn)
addMethodToObject(group, 'find', function () {return {peoples: this.peoples,count: this.peoples.length}})addMethodToObject(group, 'find', function (isMale) {if (!!isMale) {const male = this.peoples.filter(item => item.sex === 'male')return {peoples: male,count: male.length}} else {const female = this.peoples.filter(item => item.sex === 'female')return {peoples: female,count: female.length}}})addMethodToObject(group, 'find', function (elder, age) {if (!!elder) {const elder = this.peoples.filter(item => item.age >= age)return {peoples: elder,count: elder.length}} else {const younger = this.peoples.filter(item => item.age < age)return {peoples: younger,count: younger.length}}})const group = {total: 10,male: 6,female: 4,peoples: [{age: 12,sex: 'male'}, {age: 18,sex: 'female'}]}group.find()group.find(1)group.find(0, 15)
總結(jié):JS 沒有函數(shù)重載,但是可以實(shí)現(xiàn)函數(shù)重載。
學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊下方公眾號(hào)
![]()

評(píng)論
圖片
表情
