闭包是什么?运用在那些地方?
闭包理解:
- 闭包就是函数中的函数、里面的函数可以访问外面函数的变量、外面的变量是这个内部函数中的一部分。
- 函数a中有一个函数b、函数b可以访问函数a中的变量或者数据、此时形成了闭包
闭包形成的条件:
- 函数嵌套
- 内部函数访问外部函数的变量
- 内部函数被外部引用
闭包作用:
- 形成不被销毁的执行空间
- 延长变量的生命周期
- 可以实现js模块
- 缺点:使用过多引起内存溢出
使用两个文件来说明闭包
index.html
<script type="text/javascript" src="myModule.js"></script>
<script type="text/javascript">
myModule2.doSomething()
myModule2.doOtherthing()
</script>
myModule.js
(function () {
//自调用函数,特点:只执行一次
var msg = 'Beijing'//私有数据
//操作数据的函数
function doSomething() {
console.log('doSomething() '+msg.toUpperCase())
}
function doOtherthing () {
console.log('doOtherthing() '+msg.toLowerCase())
}
//向外暴露对象(给外部使用的两个方法)
window.myModule2 = {
doSomething: doSomething,
doOtherthing: doOtherthing
} })()
闭包的应用场景?
- 函数防抖
- 回调