一、模塊化編程:按模塊劃分伟件,模塊之間是獨(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));