当一个函数的返回值是另一个函数,返回的函数调用了其父级函数的参数或者局部变量,其该函数在外部被调用,此时就产生了闭包。
应用场景
1.事件防抖
在i nput 框,每次输入文字需向后台请求结果,用 change监听, 会大量向后台请求结果,导致页面卡顿
解决
function antiShake(fn,wait){
let timeOut = null;
return ()=>{
if(timeOut) clearTimeOut(timeOut);
timeOut = setTimeOut(fn,wait)
}
}
function demo(){
console.log('请求数据')
};
let telInput = document.querySelector('input');
telInput.addEventListener('input',antiShake(demo,1000))
2.用闭包模拟私有方法
私有方法:只能被同一个类的其他方法调用、防止变量更换
let Counter = (function(){
let privateCounter = 0;
function changeBy(val){
privateCounter+=val
}
return {
increment:function(){
changeBy(1)
},
decrement:function(){
changeBy(-1)
},
val:function(){
return privateCounter;
}
}
})()
console.log(Counter.value());
Counter.increment();
Counter.increment();
console.log(Counter.value());
闭包在处理速度和内存消耗上对脚本性能具有负面影响