js深层知识(柯里化,防抖,节流)

165 阅读1分钟

函数柯里化

function currying(){
	let args=[...arguments]
	let fn=function(){
		args.push(...arguments)
		return fn;
	}
	fn.toString=function(){
		return args.reduce((pre,currt)=>{
			return pre+currt;
		})
	}
	return fn ;
}
console.log(currying(1)(1)(3,3).tostring());//8
console.log(currying(1)(1)(3,3)(2,2)(1,1,1).tostring());//15

防抖

//dom
<button id="button">点击事件<button>

//需要执行的函数
function log(e){
	console.log("触发事件log"+e)
}

//防抖函数
function debounce(fn,delay){
	let timer;	
	return function(){
        let that=this;
        let args=arguments;
        clearTimeout(timer);
		timer=setTimeout(()=>{
			fn.apply(this,args);
		},delay)
	}
}
//监听事件
let logDebopunce=debounce(log,1000);
document.querySelector("#button").addEventListener("click",()=>{
	logDebopunce("hhah")
})

节流

//需要节流的方法
function setBackground(){
	let r=Math.floor(Math.random()*255);
	let g=Math.floor(Math.random()*255);
	let b=Math.floor(Math.random()*255);
	document.body.style.background=`rgb(${r},${g},${b})`
}
//节流操作
function throttle(func,delay){
	let timer;
	return function(){
		let that=this;
		let args=arguments;
		if(timer){
			return;
		}
		timer=setTimeout(function(){
			func.apply(that,args)
			timer=null;
		},delay)	
	}
}
//监听浏览器事件
window.addEventListener("resize",throttle(setBackground,1000));