概念
闭包是指有权访问另外一个函数作用域中的变量的函数。即在函数内部定义一个函数,使内部函数能够访问外部函数的变量
优点
可以创建私有变量(定义全局变量容易造成变量污染)
让变量始终保存在内存中
缺点
由于闭包常驻在内存中,如果处理不当,容易造成IE内存泄露,降低程序性能
例子
定义一个count=0,一个函数add()。要求每执行一次add,count的值就加一。
首先我们将count定义为全局变量,很容易完成上述要求
let count=0
function add(){
count++
console.log(count)
}
add() // 1
add() // 2
但是全局变量有可能带来变量污染的问题,使用闭包就可以解决这个问题。
function add(){
let count=0
return function(){
count++
console.log(count)
}
}
let a=add()
a() //1
a() //2
使用场景
函数防抖,将定时器用闭包保存
<style>
.ab {
height: 200px;
background-color: blue;
line-height: 200px;
text-align: center;
color: white;
font-size: 60px;
}
</style>
<div class="ab"></div>
<script>
function doSomething() {
ab.innerHTML = ++count
}
function debounce(func, wait) {
let timer
return function () {
clearTimeout(timer)
timer = setTimeout(func, wait)
}
}
let count = 0
let ab = document.querySelector('.ab')
ab.innerHTML=count
ab.onmousemove = debounce(doSomething, 1000)
</script>