JavaScript高階函數(shù)的好處

來(lái)源 | https://www.fly63.com/article/detial/10760
2:函數(shù)可以作為返回值輸出
高階函數(shù)實(shí)現(xiàn)AOP
/*** 織入執(zhí)行前函數(shù)* @param {*} fn*/Function.prototype.aopBefore = function(fn){console.log(this)// 第一步:保存原函數(shù)的引用const _this = this// 第四步:返回包括原函數(shù)和新函數(shù)的“代理”函數(shù)return function() {// 第二步:執(zhí)行新函數(shù),修正thisfn.apply(this, arguments)// 第三步 執(zhí)行原函數(shù)return _this.apply(this, arguments)}}/*** 織入執(zhí)行后函數(shù)* @param {*} fn*/Function.prototype.aopAfter = function (fn) {const _this = thisreturn function () {let current = _this.apply(this,arguments)// 先保存原函數(shù)fn.apply(this, arguments) // 先執(zhí)行新函數(shù)return current}}/*** 使用函數(shù)*/let aopFunc = function() {console.log('aop')}// 注冊(cè)切面aopFunc = aopFunc.aopBefore(() => {console.log('aop before')}).aopAfter(() => {console.log('aop after')})// 真正調(diào)用aopFunc()
currying(柯里化)
關(guān)于curring我們首先要聊的是什么是函數(shù)柯里化。
curring又稱部分求值。一個(gè)curring的函數(shù)首先會(huì)接受一些參數(shù),接受了這些參數(shù)之后,該函數(shù)并不會(huì)立即求值,二十繼續(xù)返回另外一個(gè)函數(shù),剛才傳入的參數(shù)在函數(shù)形成的閉包中被保存起來(lái)。待到函數(shù)中被真正的需要求值的時(shí)候,之前傳入的所有參數(shù)被一次性用于求值。
生硬的看概念不太好理解,我們來(lái)看接下來(lái)的例子
我們需要一個(gè)函數(shù)來(lái)計(jì)算一年12個(gè)月的消費(fèi),在每個(gè)月月末的時(shí)候我們都要計(jì)算消費(fèi)了多少錢(qián)。正常代碼如下:
// 未柯里化的函數(shù)計(jì)算開(kāi)銷let totalCost = 0const cost = function(amount, mounth = '') {console.log(`第${mounth}月的花銷是${amount}`)totalCost += amountconsole.log(`當(dāng)前總共消費(fèi):${totalCost}`)}cost(1000, 1) // 第1個(gè)月的花銷cost(2000, 2) // 第2個(gè)月的花銷// ...cost(3000, 12) // 第12個(gè)月的花銷
總結(jié)一下不難發(fā)現(xiàn),如果我們要計(jì)算一年的總消費(fèi),沒(méi)必要計(jì)算12次。只需要在年底執(zhí)行一次計(jì)算就行,接下來(lái)我們對(duì)這個(gè)函數(shù)進(jìn)行部分柯里化的函數(shù)幫助我們理解。
// 部分柯里化完的函數(shù)const curringPartCost = (function() {// 參數(shù)列表let args = []return function (){/*** 區(qū)分計(jì)算求值的情況* 有參數(shù)的情況下進(jìn)行暫存* 無(wú)參數(shù)的情況下進(jìn)行計(jì)算*/if (arguments.length === 0) {let totalCost = 0args.forEach(item => {totalCost += item[0]})console.log(`共消費(fèi):${totalCost}`)return totalCost} else {// argumens并不是數(shù)組,是一個(gè)類數(shù)組對(duì)象let currentArgs = Array.from(arguments)args.push(currentArgs)console.log(`暫存${arguments[1] ? arguments[1] : '' }月,金額${arguments[0]}`)}}})()curringPartCost(1000,1)curringPartCost(100,2)curringPartCost()
接下來(lái)我們編寫(xiě)一個(gè)通用的curring, 以及一個(gè)即將被curring的函數(shù)。代碼如下:
// 通用curring函數(shù)const curring = function(fn) {let args = []return function () {if (arguments.length === 0) {console.log('curring完畢進(jìn)行計(jì)算總值')return fn.apply(this, args)} else {let currentArgs = Array.from(arguments)[0]console.log(`暫存${arguments[1] ? arguments[1] : '' }月,金額${arguments[0]}`)args.push(currentArgs)// 返回正被執(zhí)行的 Function 對(duì)象,也就是所指定的 Function 對(duì)象的正文,這有利于匿名函數(shù)的遞歸或者保證函數(shù)的封裝性return arguments.callee}}}// 求值函數(shù)let costCurring = (function() {let totalCost = 0return function () {for (let i = 0; i < arguments.length; i++) {totalCost += arguments[i]}console.log(`共消費(fèi):${totalCost}`)return totalCost}})()// 執(zhí)行curring化costCurring = curring(costCurring)costCurring(2000, 1)costCurring(2000, 2)costCurring(9000, 12)costCurring()
函數(shù)節(jié)流
JavaScript中的大多數(shù)函數(shù)都是用戶主動(dòng)觸發(fā)的,一般情況下是沒(méi)有性能問(wèn)題,但是在一些特殊的情況下不是由用戶直接控制。容易大量的調(diào)用引起性能問(wèn)題。畢竟DOM操作的代價(jià)是非常昂貴的。下面將列舉一些這樣的場(chǎng)景:
window.resise事件。
mouse, input等事件。
上傳進(jìn)度
...
下面通過(guò)高階函數(shù)的方式我們來(lái)實(shí)現(xiàn)函數(shù)節(jié)流
/*** 節(jié)流函數(shù)* @param {*} fn* @param {*} interval*/const throttle = function (fn, interval = 500) {let timer = null, // 計(jì)時(shí)器isFirst = true // 是否是第一次調(diào)用return function () {let args = arguments, _me = this// 首次調(diào)用直接放行if (isFirst) {fn.apply(_me, args)return isFirst = false}// 存在計(jì)時(shí)器就攔截if (timer) {return false}// 設(shè)置timertimer = setTimeout(function (){console.log(timer)window.clearTimeout(timer)timer = nullfn.apply(_me, args)}, interval)}}// 使用節(jié)流window.onresize = throttle(function() {console.log('throttle')},600)
分時(shí)函數(shù)
節(jié)流函數(shù)為我們提供了一種限制函數(shù)被頻繁調(diào)用的解決方案。下面我們將遇到另外一個(gè)問(wèn)題,某些函數(shù)是用戶主動(dòng)調(diào)用的,但是由于一些客觀的原因,這些操作會(huì)嚴(yán)重的影響頁(yè)面性能,此時(shí)我們需要采用另外的方式去解決。
如果我們需要在短時(shí)間內(nèi)才頁(yè)面中插入大量的DOM節(jié)點(diǎn),那顯然會(huì)讓瀏覽器吃不消。可能會(huì)引起瀏覽器的假死,所以我們需要進(jìn)行分時(shí)函數(shù),分批插入。
/*** 分時(shí)函數(shù)* @param {*創(chuàng)建節(jié)點(diǎn)需要的數(shù)據(jù)} list* @param {*創(chuàng)建節(jié)點(diǎn)邏輯函數(shù)} fn* @param {*每一批節(jié)點(diǎn)的數(shù)量} count*/const timeChunk = function(list, fn, count = 1){let insertList = [], // 需要臨時(shí)插入的數(shù)據(jù)timer = null // 計(jì)時(shí)器const start = function(){// 對(duì)執(zhí)行函數(shù)逐個(gè)進(jìn)行調(diào)用for (let i = 0; i < Math.min(count, list.length); i++) {insertList = list.shift()fn(insertList)}}return function(){timer = setInterval(() => {if (list.length === 0) {return window.clearInterval(timer)}start()},200)}}// 分時(shí)函數(shù)測(cè)試const arr = []for (let i = 0; i < 94; i++) {arr.push(i)}const renderList = timeChunk(arr, function(data){let div =document.createElement('div')div.innerhtml = data + 1document.body.appendChild(div)}, 20)renderList()
惰性加載函數(shù)
在Web開(kāi)發(fā)中,因?yàn)橐恍g覽器中的差異,一些嗅探工作總是不可避免的。
因?yàn)闉g覽器的差異性,我們要常常做各種各樣的兼容,舉一個(gè)非常簡(jiǎn)單常用的例子:在各個(gè)瀏覽器中都能夠通用的事件綁定函數(shù)。
常見(jiàn)的寫(xiě)法是這樣的:
// 常用的事件兼容const addEvent = function(el, type, handler) {if (window.addEventListener) {return el.addEventListener(type, handler, false)}// for IEif (window.attachEvent) {return el.attachEvent(`on${type}`, handler)}}
這個(gè)函數(shù)存在一個(gè)缺點(diǎn),它每次執(zhí)行的時(shí)候都會(huì)去執(zhí)行if條件分支。雖然開(kāi)銷不大,但是這明顯是多余的,下面我們優(yōu)化一下, 提前一下嗅探的過(guò)程:
const addEventOptimization = (function() {if (window.addEventListener) {return (el, type, handler) => {el.addEventListener(type, handler, false)}}// for IEif (window.attachEvent) {return (el, type, handler) => {el.attachEvent(`on${type}`, handler)}}})()
這樣我們就可以在代碼加載之前進(jìn)行一次嗅探,然后返回一個(gè)函數(shù)。但是如果我們把它放在公共庫(kù)中不去使用,這就有點(diǎn)多余了。下面我們使用惰性函數(shù)去解決這個(gè)問(wèn)題:
// 惰性加載函數(shù)let addEventLazy = function(el, type, handler) {if (window.addEventListener) {// 一旦進(jìn)入分支,便在函數(shù)內(nèi)部修改函數(shù)的實(shí)現(xiàn)addEventLazy = function(el, type, handler) {el.addEventListener(type, handler, false)}} else if (window.attachEvent) {addEventLazy = function(el, type, handler) {el.attachEvent(`on${type}`, handler)}}addEventLazy(el, type, handler)}addEventLazy(document.getElementById('eventLazy'), 'click', function() {console.log('lazy ')})
一旦進(jìn)入分支,便在函數(shù)內(nèi)部修改函數(shù)的實(shí)現(xiàn),重寫(xiě)之后函數(shù)就是我們期望的函數(shù),在下一次進(jìn)入函數(shù)的時(shí)候就不再存在條件分支語(yǔ)句。
學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊下方公眾號(hào)
![]()

