一、闭包
函数内嵌套函数(返回函数),内部函数保持对外部函数的引用
闭包特性:
可以通过内部函数的引用,在调用内部函数的过程中访问外部函数的变量;
外部函数的参数不会被GC回收
内部函数时刻保持对外部函数的引用
闭包优点:不会被gc回收、避免被外部所污染,内部函数时刻被外部函数使用
闭包缺点:导致内存泄漏(内存溢出)消耗内存;内部函数要时刻保持外部函数的引用,消耗内存
闭包作用:缓存、防抖、节流函数柯里化
防抖实现:
<style>
div{
width: 300px;
height: 300px;
background-color: pink;
}
</style>
<body>
<div></div>
<script>
function dithering(fn,delay) {
var timer =null;
return function(){
if (timer) clearTimeout(timer);
timer = setTimeout(fn,delay);
}
}
let fn = dithering(function(){
console.log("移进去了");
},2000)
document.querySelector('div').onmouseenter =function(){
fn();
}
</script>
</body>
节流实现:在一定时间范围内执行
<style>
div {
width: 300px;
height: 300px;
background-color: skyblue;
}
</style>
<body>
<div></div>
<script>
function throttle(fn, delay