Javascript 高階函數

高階函數

一、參數是一個函數 二、函數返回值是一個函數 知足其中一點 就被稱爲高階函數segmentfault

函數的before

意思就是再執行一個函數以前先執行某函數。數組

//好比咱們有個方法是吃飯,吃飯以前呢咱們須要作飯。
    function eat(){
        console.log('吃飯')
    }

    //作飯
    function cooking(){
        console.log("作飯")
    }

    // 咱們要實現一個這種功能的方法  打印結果爲  作飯 、 吃飯
    // let lunch = eat.before(cooking)返回的也是一個函數
    // lunch()

    // before做爲一個函數的方法,咱們只能擴展到原型上

    Function.prototype.before = function(beforeFn){
        return (...arg)=>{ //箭頭函數的this是當前做用域的this,箭頭函數沒有arguments
            beforeFn()
            this(...arg)
        }
    }

    let lunch = eat.before(cooking)//返回的也是一個函數
    lunch()
複製代碼
類型判斷封裝
// 目前最好的辦法是用 Object.prototype.toString.call()

    //例如
    console.log(Object.prototype.toString.call('123')) //[object String]

    // 咱們若是想作一個通用方法

    // checkType('123') //能獲得正確的結果 須要怎麼作呢

    //一般咱們這麼作

    function isType(obj){
        return Object.prototype.toString.call(obj).slice(8,-1)
    }
    console.log(isType(123)) //Number  沒問題

    //不過咱們是封裝 ,咱們想直接返回Boolean

    // 這樣改
    // function checkType(obj,type){
    //     console.log(Object.prototype.toString.call(obj))
    //     return Object.prototype.toString.call(obj) === `[object ${type}]`
    // }

    // 測試
    console.log(checkType(123,"Number")) //true  沒問題  不過咱們不知足,咱們既然是封裝 確定是使用者怎麼簡單怎麼來。


    // 因而咱們想是否是能夠這樣 isNumber()、isString()....   這樣還能防止使用者 寫錯參數  例如類型全寫小寫了 等等
    //還想使用者儘可能少的傳入參數,畢竟 類型是固定的
    let types = ['String','Number','Object','Array','Function','Boolean']
    let typeUtil = {}
    // 既然咱們只須要傳入一個參數,那麼type是須要內置的
    // 須要改造checkType函數
    function checkType(type){
        return (obj)=>{
            return Object.prototype.toString.call(obj) === `[object ${type}]`
        }
    }
    types.forEach((type)=>{
        typeUtil[`is${type}`] = checkType(type)
    })

    console.log(typeUtil.isNumber(123))
複製代碼
柯里化
//    柯里化

    const add = (a,b,c,d)=>{
        return a+b+c+d
    }

    const curry = (fn,arr=[])=>{
        let len = fn.length
        return (...arg)=>{
            //累加參數 拿參數數組的長度和參數函數的長度作比較
            arr = arr.concat(arg)
            //若是參數不夠 繼續執行curry
            if(arr.length<len){
                return curry(fn,arr)
            }
            // 若是參數夠了直接執行參數函數
            return fn(...arr)
        }
    }

    let curry1 = curry(add)
    console.log(curry1(2)(3,4)(5))
複製代碼

更詳細柯里化的請移步:segmentfault.com/a/119000001…bash

函數的after
//after  意思是執行必定次數後執行一個方法,例以下邊函數  執行count次後再執行fn函數

    function after(count,fn){
        return ()=>{
            //這裏說說 count--  和 --count   很好解釋  減號在前邊就會馬上執行減一操做  在後邊 下次纔會執行
            if(--count === 0){
                fn()
            }
        }
    }
    function callBack(){
        console.log("兩次一會執行結果")
    }

    let countAfter = after(2,callBack)

    countAfter()
    countAfter()  //執行兩次之後執行結果

//    *實現解析  利用閉包的原理 存儲count數  每執行一次作一次減減* 完成條件執行函數

複製代碼
相關文章
相關標籤/搜索