闭包

当一个函数的返回值是另一个函数,返回的函数调用了其父级函数的参数或者局部变量,其该函数在外部被调用,此时就产生了闭包。

应用场景

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()); //0
Counter.increment();
Counter.increment();
console.log(Counter.value());//2

闭包在处理速度和内存消耗上对脚本性能具有负面影响
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值