JavaScript:注意事项

1. 上下文对象 闭包

  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. function init() {
  9. var pAry = document.getElementsByTagName("p");
  10. for( var i=0; i<pAry.length; i++ ) {
  11. pAry[i].onclick = function () {
  12. alert(i);
  13. }
  14. }
  15. }
  16. </script>
  17. </head>
  18. <body onload="init();">
  19. <p>产品一</p>
  20. <p>产品一</p>
  21. <p>产品一</p>
  22. <p>产品一</p>
  23. <p>产品一</p>
  24. </body>
  25. </html>

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

Js代码
  1. function init() {
  2. var pAry = document.getElementsByTagName("p");
  3. for( var 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. for( var 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. for( var 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. for( var 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. for( var i=0; i<pAry.length; i++ ) {
  4. pAry[i].onclick = new Function("alert(" + i + ");");//new一次就产生一个函数实例
  5. }
  6. }

Technorati : 闭包

原文地址:https://www.cnblogs.com/oneroom/p/1662477.html