学习JavaScript高级第八天(闭包高级应用)

it2023-05-21  74

学习JavaScript高级第八天(闭包高级应用)

1、闭包应用值惰性函数和柯理化函数

/* * JS高阶编程函数:惰性函数 + 懒 + 能只执行一次的绝不会执第二次 */ // 这样写,每调用一次都要处理兼容的问题:这完全没有必要,第一次执行知道了兼容情况,后期再调用(浏览器也没余刷新、也没有换浏览器)兼容检验是没有必要的 function getCss(ele, attr){ if(window.getComputedStyle) { return window.getComputedStyle(ele)[attr]; } else { return ele.currentStyle[attr]; } } // 方案一:页面加载就把是否兼容处理了,后期执行方法的时候直接基于变量的值判断使用哪个方法即可 let isComputed = 'getComputedStyle' in window; function getCss(ele, attr){ if(isComputed) { return window.getComputedStyle(ele)[attr]; } else { return ele.currentStyle[attr]; } } // 惰性思想:函数重定向 // + getCss 是全局函数 // + 第一次执行会形成一个闭包 function getCss(ele, attr){ if(window.getComputedStyle) { // 把全局的getCss 重定向为具体的小函数 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(document.body, 'width')); console.log(getCss(document.body, 'height')); console.log(getCss(document.body, 'padding')); /* * JS高阶函数:柯理化函数 + 预处理思想: 第一次执行大函数,形成一个闭包(原因:返回了一个小函数),把一些信息存储到闭包中(传递的实参或者当前闭包中声明的以下私有变量等信息);等到后面把返回的小函数(匿名函数)执行的时候,需要用到一些非自己私有的变量,则向上级上下文中查找(也就是把之前存储在闭包中的信息获取到) + 应用的也是闭包的机制 */ // 编写函数 fn,实现下面的功能 function fn(...arg1){ // console.log(arg1); // ...arg1 把传递进来的实参获取到,结果是一个数组 // arg1 存放第一次执行fn传递的实参 [1,2] return function(...arg2) { // arg2 存放的是紧接着执行匿名函数时传递的实参 [3] let arr = arg1.concat(arg2); return arr.reduce((total, item) => { return total+ item; }); }; } let res = fn(1,2)(3); // fn(1,2)(3) => let f = fun(1,2); f(3) console.log(res); // =>6 1+2+3 /* * reduce:数组中用来迭代遍历每一项的 arr.reduce(function([res], [item]) { }) */ /* let arr = [10,20,30,40]; var a = arr.reduce((res, item) =>{ // 把当前的回调函数执行的结果,作为下一次迭代中的[res]处理 console.log(res, item); // 10 20 // 30 30 // 60 40 return res + item; }) console.log(a); // 100 */ // 自己实现 reduce function reduce(arr, callback, init) { arr = arr.slice(0); let index = 0; // 遍历索引开始 // 检验 init 是否传递 if(typeof init === 'undefined') { init = arr[0]; // 给 init 赋值默认值 index =1; } for(let i=index; i<arr.length; i++) { init = callback(init, arr[i], i); } return init; } let arr = [10,20,30,40]; let result = reduce(arr, function(res, item, index){ console.log(index, item); return res + item; }); let result1 = reduce(arr, function(res, item, index){ console.log(index, item) return res + item; }, 100); let result2 = reduce([90], function(res, item, index){ console.log(index, item) return res + item; }); console.log(result, result1, result2)

2、闭包应用之compose组合函数

/* 在函数式编程当中又以个很重要的概念就是函数组合,实际上就是把处理数据的函数像管道一样连接起来,然后让数据穿过管道得到最终的结果。(有点像高中数学中的复合函数)例如: const add1 = (x) => x+1; const mul3 = (x) => x*3; const div2 = (x) => x/2; div2(mul3(add1(add1(0)))); // => 3 而这样的写法可读性太差了,可以构建一个compose函数,它接收多个函数作为参数(这些函数都只接收一个参数),然后compose返回的也是一个函数,从而达到解析复合函数的效果 简而言之:compose函数可以把类似于 f(g(h(x))) 这种写法简化成 compose(f,g,h)(x) 请完成 compose 函数的编写 */ function compose(...funcs){ return function(x){ if(funcs.length < 1) return x; // 如果没有传递函数,则直接返回参数 // 方案一:使用for循环 // let length = funcs.length - 1, // fun = funcs[length]; // console.log(fun); // let res = fun(0); // for(let i=length-1; i>=0;i--) { // console.log(funcs[i]); // res = funcs[i](res); // } // console.log(res); // return res; // 方案二:使用reduce funcs = funcs.reverse(); console.log(funcs); return funcs.reduce((res, item) => { console.log(res, item) return item(res); }, x) } } const add1 = (x) => x+1; const mul3 = (x) => x*3; const div2 = (x) => x/2; let re = compose(div2,mul3,add1,add1)(0); // =>3 console.log(re); // 3

3、闭包应用之函数的防抖和节流

/* * 函数的防抖(防止老年帕金森): 对于频繁触发某个操作,只识别一次(执行一次) @params: fn [function]:最后要触发执行的函数 wait [number]:“频繁”设定的界限(时间间隔) immediate [boolean]:触发多次函数时,识别第一次还是最后一次 @return 可以被调用执行的函数 */ // 主体思路:在当前点击完成后,等待wait事件,看是否还会触发第二次,如果没有触发第二次,属于非频繁操作,直接执行fn函数;如果触发了第二次,则之前的触发都不算,从当前开始重新等待wait时长 function debounce(fn, wait, immediate=false){ wait = wait || 300; let timer = null; return function(ev){ clearTimeout(timer); // 每次点击就把之前设置的定时器清除掉 // 如果是 immediate=true立即执行 console.log(timer); if(immediate && (timer === null)) { fn.call(this, ev); } // 重新设置一个新的定时器监听从当前开始,wait时间段内是否触发第二次 timer = setTimeout(()=>{ timer = null; if(!immediate) { // 不是立即执行,则执行这里 fn.call(this, ev) } }, wait); } } function handle(ev) { console.log(this, ev); console.log('防抖'); } app.onclick = debounce(handle, 500, false); */ /* * 函数的节流: 在一段频繁操作中,可以触发多次,但是触发的频率由自己制定,就是该操作一直不停的在执行,过于频繁,通过设定一个时长,让它在规定时长内触发一次,而不是一直不停的触发 @params: fn [function]:最后要触发执行的函数 wait [number]:规定函数重复执行的间隔时长 @return: 可以被调用执行的函数 */ // 方案一:使用时间戳 function throttle(fn, wait = 100) { let enterTime = new Date(); // 记录上一次触发的时间 return function(){ let backTime = new Date(); // 记录距离上一次最近触发的时间 if(backTime - enterTime > wait) { // 如果两次执行时间间隔大于设定的时间间隔,就立即执行指定的函数,并且将这次执行的时候重新记录为上一次执行时间 fn.apply(this, arguments); enterTime = backTime; } } } // 方案二:时间戳+定时器 function throttle(fn, wait=300){ let timer = null, previous = 0; // 记录上一次函数触发时的时间 return function(ev){ let now = new Date(), // 获取当前时间 cha = wait - (now - previous); // 计算设定的触发间隔时长和实际函数重复触发间隔时长的差值,即记录还差多长才能达到指定的wait时长 if(cha <= 0 ){ // 重复操作的间隔已经超过规定的wait了 clearTimeout(timer); // 清除已经存在的定时器 previous = now; // 记录当前时间 fn.call(this, ev); // 立即执行函数 } else if(!timer){ timer = setTimeout(() =>{ timer = null; previous = new Date(); fn.call(this, ev) },cha) } } } function handle() { console.log('节流'); } // window.onscroll = handle; // 在滚动的过程中,浏览器有最快反应时间(5~6ms 13~17ms),只要反应过来就会执行一次 window.onscroll = throttle(handle, 500); // 我们控制滚动过程中该函数300ms才触发一次 /* * 总结: 防抖:点击做啥事,一般都是用防抖 节流:滚动、文本框输入等一般用节流 */
最新回复(0)