Notation +function() {} ใช้เพื่อบังคับให้ parser จัดการสิ่งที่ตามหลัง + เป็น expression ใช้สำหรับฟังก์ชันที่ถูก invoke ทันที (IIFE):
+function() { alert("Demo!"); }();
แต่ + หน้าฟังก์ชันเป็นแค่สัญลักษณ์หนึ่ง สัญลักษณ์อื่นๆ ก็ใช้ได้ เช่น !, -, ~ และ parentheses ก็ได้:
(function() { alert("Demo!"); })();
หรือแบบนี้ก็ได้:
(function() { alert("Demo!"); }());
IIFE (Immediately Invoked Function Expression) Patterns
| Pattern | คำอธิบาย |
|---|---|
(function(){})() | Classic - กลุ่มด้วย parentheses แล้ว invoke |
(function(){}()) | Variant - invoke ภายใน parentheses |
!function(){}() | Unary operator บังคับ expression context |
+function(){}() | Unary + บังคับ expression context |
-function(){}() | Unary - บังคับ expression context |
~function(){}() | Bitwise NOT บังคับ expression context |
void function(){}() | void operator บังคับ expression context |
ทำไมต้องบังคับ Expression Context?
เพราะ function() {} เริ่มต้นด้วยคีย์เวิร์ด function → parser คิดว่าเป็น Function Declaration (ต้องมีชื่อ) การใส่ operator หรือ parentheses ทำให้มันกลายเป็น Function Expression ซึ่งสามารถ invoke ทันทีได้
สมัยใหม่: ใช้ Block Scope หรือ Modules
// ES6+ Block scope
{
const x = 1;
// x ไม่ออกนอกบล็อก
}
// ES Modules - แต่ละไฟล์เป็น scope ของตัวเอง
// ไม่ต้อง IIFE แล้ว