js闭包演示

有个网友问了个问题,如下的html,为什么每次输出都是5

Html代码 
  1. <html >   
  2. <head>   
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />   
  4. <title>闭包演示</title>   
  5. <style type="text/css">   
  6. </style>   
  7. <script type="text/javascript">   
  8.   
  9. function init() {   
  10.     var pAry = document.getElementsByTagName("p");   
  11.     for( var i=0; i<pAry.length; i++ ) {   
  12.          pAry[i].onclick = function() {   
  13.          alert(i);   
  14.     }   
  15.   }   
  16. }   
  17. </script>   
  18. </head>   
  19. <body onload="init();">   
  20. <p>产品一</p>   
  21. <p>产品一</p>   
  22. <p>产品一</p>   
  23. <p>产品一</p>   
  24. <p>产品一</p>   
  25. </body>   
  26. </html>   

 解决方式有两种, 
1、将变量 i 保存给在每个段落对象(p)上

Js代码 
  1. function init() {   
  2.   var pAry = document.getElementsByTagName("p");   
  3.   forvar i=0; i<pAry.length; i++ ) {   
  4.      pAry[i].i = i;   
  5.      pAry[i].onclick = function() {   
  6.         alert(this.i);   
  7.      }   
  8.   }   
  9. }   

2、将变量 i 保存在匿名函数自身 

Java代码 
  1. function init2() {   
  2.   var pAry = document.getElementsByTagName("p");   
  3.   for( var i=0; i<pAry.length; i++ ) {     
  4.    (pAry[i].onclick = function() {   
  5.         alert(arguments.callee.i);   
  6.     }).i = i;   
  7.   }   
  8. }   

 再增加3种

 

3、加一层闭包,i以函数参数形式传递给内层函数

Js代码 
  1. function init3() {   
  2.   var pAry = document.getElementsByTagName("p");   
  3.   forvar i=0; i<pAry.length; i++ ) {   
  4.    (function(arg){       
  5.        pAry[i].onclick = function() {       
  6.           alert(arg);   
  7.        };   
  8.    })(i);//调用时参数   
  9.   }   
  10. }   

4、加一层闭包,i以局部变量形式传递给内存函数

Js代码 
  1. function init4() {   
  2.   var pAry = document.getElementsByTagName("p");   
  3.   forvar i=0; i<pAry.length; i++ ) {     
  4.     (function () {   
  5.       var temp = i;//调用时局部变量   
  6.       pAry[i].onclick = function() {     
  7.         alert(temp);     
  8.       }   
  9.     })();   
  10.   }   
  11. }   

5、加一层闭包,返回一个函数作为响应事件(注意与3的细微区别)

Js代码 
  1. function init5() {   
  2.   var pAry = document.getElementsByTagName("p");   
  3.   forvar i=0; i<pAry.length; i++ ) {     
  4.    pAry[i].onclick = function(arg) {   
  5.        return function() {//返回一个函数   
  6.        alert(arg);   
  7.      }   
  8.    }(i);   
  9.   }   
  10. }  

又有一种方法

 

6、用Function实现,实际上每产生一个函数实例就会产生一个闭包

Js代码 
  1. function init6() {   
  2.     var pAry = document.getElementsByTagName("p");   
  3.     forvar i=0; i<pAry.length; i++ ) {     
  4.       pAry[i].onclick = new Function("alert(" + i + ");");//new一次就产生一个函数实例  
  5.     }   
  6. }  
 from:http://zhouyrt.javaeye.com/blog/250073

posted on 2009-06-17 11:11  房客  阅读(536)  评论(1编辑  收藏  举报

导航