3_立即执行函数.html 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <ul>
  10. <li>1</li>
  11. <li>2</li>
  12. <li>3</li>
  13. <li>4</li>
  14. <li>5</li>
  15. <li>6</li>
  16. </ul>
  17. <script>
  18. var aLi = document.getElementsByTagName('li');
  19. for (var i = 0; i < aLi.length; i++) {
  20. // aLi[i].index = i;
  21. // aLi[i].onclick = function () {
  22. // console.log(this.index);
  23. // }
  24. (function(a){
  25. aLi[a].onclick = function(){
  26. console.log(a);
  27. }
  28. })(i);
  29. }
  30. // var foo = function(){
  31. // console.log("hello");
  32. // }
  33. // foo();
  34. // console.log(foo);
  35. // 立即执行函数
  36. // (function(){
  37. // console.log("hello");
  38. // })();
  39. // var a = 20;
  40. // function foo(){
  41. // var a = 10;
  42. // function foo2(){
  43. // // var a = 30;
  44. // console.log(a++);
  45. // }
  46. // // foo2();
  47. // // foo2();
  48. // return foo2;
  49. // }
  50. // var foo3 = foo();
  51. // // console.log(foo3)
  52. // foo3();
  53. // foo3();
  54. // 1. 为了防止变量名冲突
  55. // 2. 为了防止全局变量污染
  56. </script>
  57. </body>
  58. </html>