javascipt

闭包

2019-10-20  本文已影响0人  杰克_王_
<!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>
上一篇下一篇

猜你喜欢

热点阅读