JavaScript的IIFE,即时执行方法

IIFE :immediately-invoked function expression

(1)标准写法

1 (function(window, document, undefined) {
2     //你的代码 
3 })(window, document);

例如:

1 //jQuery
2 (function($){})(jQuery);
3 //mui
4 (function($){})(mui);

(2)作用域Scope

JavaScript有function作用域,所以function首先创建一个私有的作用域,在执行的时候都会创建一个执行上下文。

 1 var logMyName = function(name) {
 2     console.log(name);
 3 };
 4 logMyName('李四');
 5 
 6 var logMyName = (function(name) {
 7     console.log(name);
 8 })('王五');
 9 
10 var a = ! function() {
11     return true;
12 }();
13 console.log(a); // 打印输出 false  
14 
15 var b = (function() {
16     return true;
17 })();
18 console.log(b); // 打印输出 true  
19 
20 //强制JavaScript识别代码(一般很少这么用)
21 ! function() {
22     // ...  
23 }();
24 
25 + function() {
26     // ...  
27 }();
28 
29 - function() {
30     // ...  
31 }();
32 
33 ~ function() {
34     // ...  
35 }();
1 (function($, window, document, undefined) {
2     // 使用 $ 指向 jQuery,比如:  
3     // $(document).addClass('test');  
4 })(jQuery, window, document);
5 
6 (function(a, b, c, d) {
7     // 代码会被压缩为:  
8     // a(c).addClass('test');  
9 })(jQuery, window, document);

转自:http://rensanning.iteye.com/blog/2080429