寫成 var fun = function(){} 時,那個 function 沒有名字,就是匿名函數。但匿名函數沒有名稱也沒有引用,要怎麼執行?答案是用各種方式「強制」把它變成表達式,然後立刻呼叫。這篇文章把常見與不常見的寫法都收集起來。
問題出在 function(){}() 這種寫法會被解析器當成函數宣告,而函數宣告必須有名字,於是語法錯誤。解法是在前面加上任何一個運算子,讓引擎改用「表達式」的規則來解析。
方式 1:括號包住並把引數放在裡面
(function(x,y){ alert(x+y); return x+y; }(3,4));
方式 2:括號包住,引數放在外面
(function(x,y){ alert(x+y); return x+y; })(3,4);
這也是 jQuery、MooTools 等函式庫最愛的形式。
方式 3:使用 void
void function(x) { x = x-1; alert(x); }(9);
方式 4:使用 +/- 運算子
-function(x,y){ alert(x+y); return x+y; }(3,4); +function(x,y){ alert(x+y); return x+y; }(3,4); --function(x,y){ alert(x+y); return x+y; }(3,4); ++function(x,y){ alert(x+y); return x+y; }(3,4);
方式 5:使用波浪符 ~
~function(x, y) { alert(x+y); return x+y; }(3, 4);
方式 6:放進陣列字面值裡
[function(){ console.log(this) // 浏覽器得控制台輸出window }(this)]
方式 7:前面加 typeof
typeof function(){ console.log(this) // 浏覽器得控制台輸出window }(this)
方式 8:前面加 delete
delete function(){ console.log(this) // 浏覽器得控制台輸出window }(this)
方式 9:前面加 void
void function(){ console.log(this) // 浏覽器得控制台輸出window }(this)
方式 10、11:用 new(傳參與不傳參)
new function(win){ console.log(win) // window }(this)
new function(){ console.log(this) // 這裡的this就不是window了 }
方式 12:逗號運算子
(0, function(){ console.log(this) // window })();
方式 13:按位異或 ^
^function(){ console.log(this) // window }();
function(x,y){ alert(x+y); return x+y; }(3,4);
少了最外層的括號或前置運算子,引擎會把它當成宣告,直接丟語法錯誤。
最經典的帶參數寫法:
(function(o) { alert(o); })('water');
用 arguments.callee 做出鏈式呼叫:
(function(o) { console.log(o); return arguments.callee; })('water')('down');
以及幾種比較少見但確實能跑的:
~(function(){ alert('water'); })();//寫法有點酷~
void function(){ alert('water'); }();//據說效率最高~
+function(){ alert('water'); }();
-function(){ alert('water'); }();
!function(){ alert('water'); }();
(function(){ alert('water'); }());//有點強制執行的味道~
雖然寫法很多,但實際專案請統一用 (function(){ ... })(); 或 (function(){ ... }()); 這兩種。原因很單純:可讀性。用 ! 或 ~ 雖然簡短,但後接手的人得先想一下「這是在幹嘛」。IIFE 的主要價值在於建立獨立作用域,避免變數污染全域——在 ES6 有了 let 與區塊作用域之後,這個需求已經大幅降低,但在需要執行期隔離或封裝模組時,它依然是標配手法。