02.IIFE.html 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <!--
  11. 1.理解
  12. *全称:Immediately-Invoked Function Expression,又叫匿名函数自调用
  13. 2.作用
  14. *隐藏实现
  15. *不会污染外部(全局)命名空间
  16. *用它来编写js模块
  17. -->
  18. <script>
  19. // (function () { //匿名函数自调用
  20. // console.log('---------');
  21. // })();
  22. // (function () { //匿名函数自调用
  23. // var a = 3;
  24. // console.log(a+3);//输出6
  25. // })();
  26. // var a = 4;
  27. // console.log(a);//输出4
  28. (function(){
  29. var a = 1;
  30. function test(){
  31. console.log(++a);
  32. };
  33. function test2(){
  34. console.log('test2()');
  35. };
  36. window.$ = function(){ //向外暴露一个全局函数
  37. return{
  38. test:test
  39. };
  40. };
  41. })();
  42. $().test(); //1.$是一个函数 2.$执行后返回的是一个对象
  43. </script>
  44. </body>
  45. </html>