1、创建私有作用域
(function(){
const x = 1;
function test(){
console.log(x);
}
test();
})()
2.函数柯里化
闭包在柯里化函数中的作用主要是把参数缓存起来等凑齐参数再执行。
function curry(fn, ...parmas){
const len = fn.length;
const casheParams = [ ...parmas ]; // 缓存参数
return function(...newParams){
casheParams.push(...newParams);
if(casheParams.length < len){ // 还差参数先不执行
return curry(fn, ...casheParams);
}
return fn(...casheParams);
}
}
function add(a, b, c){
return a + b + c;
}
console.log(curry(add, 1, 2, 3)()); // 6
const curryFunc = curry(add, 1);
console.log(curryFunc(2)(3)); // 6
3、函数记忆
闭包在记忆函数中的应用是把执行结果缓存起来,下次执行函数时先搜索记忆字典里面有没有执行过相同的case,有则直接返回无需重复计算。
function memoryFun(fn){
const map = new Map();
return function(...params){
const key = params.toString();
if(map.has(key)){
return map.get(key);
}
const result = fn(...params);
map.set(key, result); // 用闭包把计算过的结果缓存起来
return result;
}
}
function Mult(){
let result = 1;
for(let i = 0, len = arguments.length; i < len; i++){
result *= arguments[i];
}
return result;
}
const testFun = memoryFun(Mult);
testFun(1, 2, 3);
testFun(1, 2, 3);
4、防抖
防抖函数就是相同事件不再触发后到设定时间才会执行相应回调的函数,闭包在这里的应用就是缓存回调函数
function debounce(func, wait) {
var timeout;
return function () {
clearTimeout(timeout)
timeout = setTimeout(func, wait);
}
}
window.onresize = debounce(callBackFun, delayTime);