JS高階編程技巧[ 模塊化、惰性思想窍侧、柯里化县踢、組合函數(shù) ]

一、模塊化編程:按模塊劃分伟件,模塊之間是獨(dú)立的「也能相互調(diào)用」

  • 單例設(shè)計(jì)模式
  • AMD require.js
  • CMD sea.js 「CommonJS」
  • CommonJS Node.js
  • ES6Module

基于閉包避免全局變量污染
想實(shí)現(xiàn)各版塊之間方法的相互調(diào)用:把需要供別人調(diào)用的方法暴露到全局

  • window.xxx=xxx 暴露比較多的情況下硼啤,還是會(huì)產(chǎn)生全局污染
  • 基于閉包+單例設(shè)計(jì)思想 ->高級單例設(shè)計(jì)模式 「早期的模塊化思想」
    代碼如下:
let searchModule = (function () {
    let wd = "";
    function query() {
        // ...
    }
    function submit() {
        // ...
    }
    return {
        // submit:submit
        submit,
        query
    };
})();

let weatherModule = (function () {
    let city = "";
    function submit() {
        // ...
    }
    return {
        submit
    };
})();

let skinModule = (function () {
    let wd = "";
    function search() {
        // ...
    }
    searchModule.submit();
    return {};
})();

二、惰性函數(shù)

舉個(gè)例子:比如獲取元素的樣式:

元素.style.xxx 獲取行內(nèi)樣式

  • 盒子模型屬性「外加:getBoundingClientRect」
  • 獲取所有經(jīng)過瀏覽器計(jì)算過的樣式
  • 標(biāo)準(zhǔn):getComputedStyle
  • IE6~8:currentStyle

代碼實(shí)現(xiàn):每次都會(huì)執(zhí)行一次判斷

let box = document.querySelector('.box');

let isCompatible = typeof getComputedStyle !== "undefined" ? true : false;
const getCss = function getCss(element, attr) {
    if (isCompatible) {
        return window.getComputedStyle(element)[attr];
    }
    return element.currentStyle[attr];
};
console.log(getCss(box, 'width'));
console.log(getCss(box, 'backgroundColor'));
console.log(getCss(box, 'height'));

利用函數(shù)的重構(gòu)【閉包】:判斷代碼只執(zhí)行一次斧账,getcss賦值新的函數(shù)谴返,惰性處理

// 核心:函數(shù)重構(gòu)「閉包」
let getCss = function (ele, attr) {
    if (typeof getComputedStyle !== "undefined") {
        getCss = function (ele, attr) {
            return window.getComputedStyle(ele)[attr];
        };
    } else {
        getCss = function (ele, attr) {
            return ele.currentStyle[attr];
        };
    }
    // 保證第一次也獲取值
    return getCss(ele, attr);
};

console.log(getCss(box, 'width'));
console.log(getCss(box, 'backgroundColor'));
console.log(getCss(box, 'height'));

三煞肾、柯里化

函數(shù)柯理化:閉包的進(jìn)階應(yīng)用

  • 核心:“預(yù)先處理/預(yù)先存儲(chǔ)”「利用閉包的保存作用:凡是形成一個(gè)閉包,存儲(chǔ)一些信息嗓袱,供其下級上下文調(diào)取使用的扯旷,都是柯理化思想」
    代碼:
 const fn = (...params) => {
    // params->[1,2]
    return (...args) => {
        // args->[3]
        return params.concat(args).reduce((total, item) => {
            return total + item;
        });
    };
};
let total = fn(1, 2)(3);
console.log(total); //=>6 
const curring = () => {
    let arr = [];
    const add = (...params) => {
        arr = arr.concat(params);
        return add;
    };
    add.toString = () => {
        return arr.reduce((total, item) => {
            return total + item;
        });
    };
    return add;
};
let add = curring();
let res = add(1)(2)(3);
console.log(res); //->6

add = curring();
res = add(1, 2, 3)(4);
console.log(res); //->10

add = curring();
res = add(1)(2)(3)(4)(5);
console.log(res); //->15 
記錄執(zhí)行次數(shù):面試題
const curring = n => {
    let arr = [],
        index = 0;
    const add = (...params) => {
        index++;
        arr = arr.concat(params);
        if (index >= n) {
            return arr.reduce((total, item) => {
                return total + item;
            });
        }
        return add;
    };
    return add;
};
let add = curring(5);
res = add(1)(2)(3)(4)(5);
console.log(res); //->15 

四、組合函數(shù)

在函數(shù)式編程當(dāng)中有一個(gè)很重要的概念就是函數(shù)組合索抓, 實(shí)際上就是把處理數(shù)據(jù)的函數(shù)像管道一樣連接起來, 然后讓數(shù)據(jù)穿過管道得到最終的結(jié)果毯炮。

例如:
    const add1 = x => x + 1;
    const mul3 = x => x * 3;
    const div2 = x => x / 2;
    div2(mul3(add1(add1(0)))); //=>3

而這樣的寫法可讀性明顯太差了逼肯,我們可以構(gòu)建一個(gè)compose函數(shù),它接受任意多個(gè)函數(shù)作為參數(shù)(這些函數(shù)都只接受一個(gè)參數(shù))桃煎,然后compose返回的也是一個(gè)函數(shù)篮幢,達(dá)到以下的效果:

    const operate = compose(div2, mul3, add1, add1)
    operate(0) //=>相當(dāng)于div2(mul3(add1(add1(0)))) 
    operate(2) //=>相當(dāng)于div2(mul3(add1(add1(2))))

function compose(...funcs) {
    let len = funcs.length;
    if (len === 0) return x => x;
    if (len === 1) return funcs[0];
    return function operate(...args) {
        return funcs.reduceRight((result, item) => {
            if (Array.isArray(result)) {
                return item(...result);
            }
            return item(result);
        }, args);
    };
}
let operate = compose(div2, mul3, add1, add1);
console.log(operate(0)); 

react中redux中的compose函數(shù):

function compose(...funcs) {
    if (funcs.length === 0) {
        return x => {
            return x;
        };
    }
    if (funcs.length === 1) {
        return funcs[0];
    }
    // funcs -> [div2, mul3, add1, add1]
    return funcs.reduce((a, b) => {
        // 第一次 每一次迭代,執(zhí)行回調(diào)函數(shù)为迈,都產(chǎn)生一個(gè)閉包三椿,存儲(chǔ)a/b,返回的小函數(shù)中后期使用的a/b就是這個(gè)閉包中的
        //   a -> div2
        //   b -> mul3
        //   return x=>a(b(x)) @1
        // 第二次
        //   a -> @1
        //   b -> add1
        //   return x=>a(b(x)) @2
        // 第三次
        //   a -> @2
        //   b -> add1
        //   return x=>a(b(x)) @3
        return x => {
            return a(b(x));
        };
    }); //=>return @3; 賦值給外面的operate
}
const operate = compose(div2, mul3, add1, add1);
console.log(operate(0)); 

reduce底層實(shí)現(xiàn)原理:

Array.prototype.reduce = function reduce(callback, initial) {
    let self = this, // this -> arr
        i = 0,
        len = self.length,
        item,
        result;
    if (typeof callback !== "function") throw new TypeError('callback must be an function!');
    if (typeof initial === "undefined") {
        // 初始值不設(shè)置葫辐,讓初始值是數(shù)組第一項(xiàng)搜锰,并且從數(shù)組第二項(xiàng)開始遍歷
        initial = self[0];
        i = 1;
    }
    result = initial;

    // 循環(huán)數(shù)組中的每一項(xiàng)
    for (; i < len; i++) {
        item = self[i];
        result = callback(result, item, i);
    }
    return result;
};

let arr = [10, 20, 30, 40];
console.log(arr.reduce((result, item, index) => {
    return result + item;
}));
console.log(arr.reduce((result, item) => {
    return result + item;
}, 0));
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市耿战,隨后出現(xiàn)的幾起案子蛋叼,更是在濱河造成了極大的恐慌,老刑警劉巖剂陡,帶你破解...
    沈念sama閱讀 218,036評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件狈涮,死亡現(xiàn)場離奇詭異,居然都是意外死亡鸭栖,警方通過查閱死者的電腦和手機(jī)歌馍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來晕鹊,“玉大人松却,你說我怎么就攤上這事∧筇猓” “怎么了玻褪?”我有些...
    開封第一講書人閱讀 164,411評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長公荧。 經(jīng)常有香客問我带射,道長,這世上最難降的妖魔是什么循狰? 我笑而不...
    開封第一講書人閱讀 58,622評論 1 293
  • 正文 為了忘掉前任窟社,我火速辦了婚禮券勺,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘灿里。我一直安慰自己关炼,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,661評論 6 392
  • 文/花漫 我一把揭開白布匣吊。 她就那樣靜靜地躺著儒拂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪色鸳。 梳的紋絲不亂的頭發(fā)上社痛,一...
    開封第一講書人閱讀 51,521評論 1 304
  • 那天,我揣著相機(jī)與錄音命雀,去河邊找鬼蒜哀。 笑死,一個(gè)胖子當(dāng)著我的面吹牛吏砂,可吹牛的內(nèi)容都是我干的撵儿。 我是一名探鬼主播,決...
    沈念sama閱讀 40,288評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼狐血,長吁一口氣:“原來是場噩夢啊……” “哼淀歇!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起氛雪,我...
    開封第一講書人閱讀 39,200評論 0 276
  • 序言:老撾萬榮一對情侶失蹤房匆,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后报亩,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體浴鸿,經(jīng)...
    沈念sama閱讀 45,644評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,837評論 3 336
  • 正文 我和宋清朗相戀三年弦追,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了岳链。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,953評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡劲件,死狀恐怖掸哑,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情零远,我是刑警寧澤苗分,帶...
    沈念sama閱讀 35,673評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站牵辣,受9級特大地震影響摔癣,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,281評論 3 329
  • 文/蒙蒙 一择浊、第九天 我趴在偏房一處隱蔽的房頂上張望戴卜。 院中可真熱鬧,春花似錦琢岩、人聲如沸投剥。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽江锨。三九已至,卻和暖如春糕篇,著一層夾襖步出監(jiān)牢的瞬間泳桦,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評論 1 269
  • 我被黑心中介騙來泰國打工娩缰, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人谒府。 一個(gè)月前我還...
    沈念sama閱讀 48,119評論 3 370
  • 正文 我出身青樓拼坎,卻偏偏與公主長得像,于是被迫代替她去往敵國和親完疫。 傳聞我的和親對象是個(gè)殘疾皇子泰鸡,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,901評論 2 355

推薦閱讀更多精彩內(nèi)容