对js 闭包的理解

概念

闭包是指有权访问另外一个函数作用域中的变量的函数。即在函数内部定义一个函数,使内部函数能够访问外部函数的变量

优点

可以创建私有变量(定义全局变量容易造成变量污染)
让变量始终保存在内存中

缺点

由于闭包常驻在内存中,如果处理不当,容易造成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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值