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

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

