閉包的優勢及使用閉包的注意點

一. 閉包的優勢:閉包

1)  減小全局變量函數

 <script>
        function f(){
           var a = 0;
            return function () {
                a++;
                alert(a);
            }
        }
        var result = f();
        result(); //1
        result(); //2
</script>

2) 減小傳遞給函數的參數數量spa

<script>
        function calFactory(base){
            return function (max) {
                var total = 0;
                for(var i = 1; i <= max; i++){
                    total += i;
                }
                return total + base;
            }
        }

        var adder = calFactory(2);
        alert(adder(3)); //8
</script>

3) 封裝code

<script>
        (function () {
            var m = 0;
            function getM(){
                return m;
            }
            function setM(val){
                m = val;
            }
            window.g = getM;
            window.f = setM;
        })();
        f(12);
        alert(g()); //12
</script>

 

二. 使用閉包的注意點:blog

1) 對捕獲的變量只引用不是賦值ip

<script>
        function f(){
            var num = 1;
            function g(){//g scope
                alert(num);
            }
            num++;
            g();
        }
        f(); //f LE
</script>

2) 父函數每調用一次會產生不一樣的閉包get

<script>
        function f(){
            var num = 1;
            return function () {
                num++;
                alert(num)
            }
        }
        var result1 = f(); //LE1
        result1(); //2
        result1(); //3
        var result2 = f(); //LE2,每調用一次會產生一個新的詞法環境
        result2(); //2
        result2(); //3
</script>

3) 循環io

<body>
    <div id = "1">1</div>
    <div id = "2">2</div>
    <div id = "3">3</div>
    <script>
//        for(var i = 1; i <= 3; i++){
//            var ele = document.getElementById(i);
//            ele.onclick = function () {
//                alert(i); //4 4 4
//            }
//        }
        for(var i = 1; i <= 3; i++){
            var ele = document.getElementById(i);
            ele.onclick = (function (id) {
                return function (){
                    alert(id); //1 2 3
                }
            })(i);
        }

    </script>
</body>
相關文章
相關標籤/搜索