第三十六节 JavaScript封闭函数的功能

 1 <!-- 封闭函数的功能:为了解决变量覆盖问题,特别是进行功能迭代的时候,可以用封闭函数,避免前后命名冲突导致的bug -->
 2 <!DOCTYPE html>
 3 <html lang="en">
 4 <head>
 5     <meta charset="UTF-8">
 6     <title>Document</title>
 7     <script type="text/javascript">
 8         // 封闭函数,一定义就调用
 9         (function(){
10                     alert('hello world!')
11                 })();
12         // 封闭函数的第二种写法
13         !function(){
14                     alert('hello world!')
15                 }();
16         // 封闭函数的第三种写法
17         ~function(){
18                     alert('hello world!')
19                 }();
20         // 可以在封闭函数前加一个分号';',可以避免js压缩的时候出错。
21 
22 
23         var iNum = 12;
24 
25         // 定义一个外部函数将功能函数包裹起来,实现解决命名冲突的问题    
26         // function fnMyalert(){
27         //     alert('hello')
28         // }
29 
30         // (function fnx(){
31         //     var iNum = 24;
32         //     function fnMyalert(){
33         //         alert('world')
34         //     }
35         // })();
36     </script>
37 </head>
38 <body>
39     
40 </body>
41 </html>
原文地址:https://www.cnblogs.com/kogmaw/p/12493074.html