| 方式 | 語法 | 提升 | 作用域 | this 綁定 | 適用場景 |
|---|---|---|---|---|---|
| 函數宣告 | function fn() {} | 整體提升 | 詞法 | 動態 | 工具函數、全域 API |
| Function 建構子 | new Function('x', 'return x*2') | 無 | 全域 | 全域 | 動態代碼生成(極少用) |
| 函數表達式 | var fn = function() {} | 變數提升 | 詞法 | 動態 | 回調、模組模式、條件定義 |
| 函數直接量/箭頭函數 | const fn = () => {} | 變數提升 | 詞法 | 靜態(外層) | 現代開發首選、回調、方法 |
function distance(x1, y1, x2, y2) {
var dx = x2 - x1;
var dy = y2 - y1;
return Math.sqrt(dx*dx + dy*dy);
}
// 整體提升,宣告前可呼叫
var multiply = new Function('x', 'y', 'return x * y;');
// 等同於 function multiply(x, y) { return x * y; }
/* 特性 */
- 參數:字串形式,最後一個為函數主體
- 每次調用都重新編譯(效能極差)
- 作用域固定為全域(無閉包)
- 僅用於極少數「運行時動態生成函數」場景
// 匿名
var square = function(x) { return x * x; };
// 具名(NFE)—— 推薦用於遞迴與除錯
var factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1); // 內部用 fact 遞迴
};
// NFE 優勢:
// 1. 除錯堆疊顯示 'fact' 而非 anonymous
// 2. 遞迴不依賴外部變數名(重構安全)
// 3. 函數名僅內部可見,不污染外部作用域
// 定義並立即執行
var result = (function(x) { return x * x; })(10); // 100
// 模組模式:建立私有作用域
var Counter = (function() {
var count = 0; // 私有變數
return {
increment: function() { return ++count; },
getCount: function() { return count; }
};
})();
Counter.increment(); // 1
Counter.getCount(); // 1
// count 無法從外部直接存取
var y = 'global';
function testScope() {
var y = 'local';
return new Function('return y;'); // 捕獲全域
}
console.log(testScope()()); // 'global' ⚠️
// 函數表達式捕獲詞法作用域
function testScope2() {
var y = 'local';
return function() { return y; };
}
console.log(testScope2()()); // 'local' ✅
new Function() 或 eval()// 1. 預設使用 const + 箭頭函數
const add = (a, b) => a + b;
const greet = name => console.log(`Hello, ${name}`);
// 2. 需要動態 this 或 arguments → 具名函數表達式
const handler = function handleEvent(e) {
console.log(this, arguments);
};
// 3. 類別方法、原型方法 → 簡潔語法
class User {
constructor(name) { this.name = name; }
sayHi() { console.log(this.name); } // 非箭頭函數,保留 this
}
// 4. 避免 Function 建構子,若必須動態生成 → new Function() 但隔離在模組初始化階段
理解四種方式的本質差異,根據場景選擇最適合的工具,是 JavaScript 開發者的基本功。