Immediately Invoked Function Expression (IIFE):定義函式並**立即執行**,建立獨立作用域,避免汙染全域命名空間。
// 寫法 1:函式表達式包在括號內,再呼叫
(function() {
// 私有作用域
const secret = 'hidden';
console.log('IIFE 執行了');
})();
// 寫法 2:void 運算子 (較少見)
void function() { console.log('也可'); }();
// 寫法 3:一元運算子
+function() { console.log('同上'); }();
!function() { console.log('同上'); }();
~function() { console.log('同上'); }();
(function(global, $, undefined) {
// global -> window, $ -> jQuery, undefined -> 真正的 undefined (防止被覆寫)
$.fn.myPlugin = function() { return this.css('color', 'red'); };
})(window, jQuery);
const Counter = (function() {
// 私有狀態
let count = 0;
const MAX = 100;
// 公開 API
return {
increment() { return ++count; },
decrement() { return --count; },
getValue() { return count; },
reset() { count = 0; },
isMax() { return count >= MAX; }
};
})();
// 使用
Counter.increment(); // 1
Counter.increment(); // 2
console.log(Counter.getValue()); // 2
// count 完全不可從外部存取
const ApiClient = (function() {
const baseUrl = '/api/v1';
const tokenKey = 'auth_token';
function getToken() { return localStorage.getItem(tokenKey); }
function authHeader() { return { 'Authorization': 'Bearer ' + getToken() }; }
async function request(path, options = {}) {
const res = await fetch(baseUrl + path, {
...options,
headers: { 'Content-Type': 'application/json', ...authHeader(), ...options.headers }
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
// 公開介面
return {
getUser: () => request('/user/me'),
login: (cred) => request('/auth/login', { method: 'POST', body: JSON.stringify(cred) }),
logout: () => localStorage.removeItem(tokenKey)
};
})();
// counter.js
let count = 0; // 模組私有
export const increment = () => ++count;
export const getValue = () => count;
// main.js
import { increment, getValue } from './counter.js';
increment(); console.log(getValue());
// 錯誤:全部印 3
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// 正確 1:IIFE 捕捉當前 i
for (var i = 0; i < 3; i++) {
(function(i) { setTimeout(() => console.log(i), 100); })(i);
}
// 正確 2:let 區塊作用域 (ES6)
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 0,1,2
}
核心概念: IIFE = 建立私有作用域的唯一手段 (ES6 前)。閉包 = 函式記住並存取其詞法作用域變數。兩者結合構成 JavaScript 模組化、封裝、狀態管理的基石。