闭包

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>闭包</title>
    <style>
        ul>li {
            list-style: cjk-earthly-branch;
            border: 1px red solid;
            margin-bottom: 5px;
        }
    </style>
</head>

<body>
    <script>
        // 闭包特点
        // 1. 函数嵌套函数
        // 2. 函数内部可以引用外部的参数和变量
        // 3. 参数和变量不会被垃圾回收机制回收,而是保存在内存中

        function getName() {
            var count = 0;

            function getCount() {
                count++;
                console.log(count);
                return count;
            }

            return getCount;
        }

        var c1 = getName();
        console.log(c1);
        console.log(c1());
        console.log(c1());
        console.log(c1());

        c1 = getName();
        console.log(c1);
        console.log(c1());
        console.log(c1());
    </script>

    <script>
        // 闭包的好处
        // 1. 希望变量存在缓存中
        // 2. 避免全局污染
        // 3. 保护私有成员

        var test = (function () {
            var a = 10;

            return function () {
                a++;
                console.log(a);
            }
        })(); // 立即执行,返回内部函数
        test();
        test();
    </script>

    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
    </ul>

    <script>
        var ali = document.querySelectorAll('li');
        for (var i = 0; i < ali.length; i++) {
            (function (i) {
                console.log(`绑定第 ${i + 1} 个元素的点击事件`);
                ali[i].onclick = function () {
                    console.log(`点击了第 ${i + 1} 个 li 元素,元素为:`, this);
                }
            })(i)

            // console.log(i);
        }
    </script>
</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值