闭包的优点及使用闭包的注意点
一. 闭包的优点:
1) 减少全局变量
<script> function f(){ var a = 0; return function () { a++; alert(a); } } var result = f(); result(); //1 result(); //2 </script>
2) 减少传递给函数的参数数量
<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) 封装
<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>
二. 使用闭包的注意点:
1) 对捕获的变量只引用不是赋值
<script> function f(){ var num = 1; function g(){//g scope alert(num); } num++; g(); } f(); //f LE </script>
2) 父函数每调用一次会产生不同的闭包
<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) 循环
<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>