JS 函數簽名**不包含參數類型/個數**,函數聲明會被後者覆蓋:
function add(a, b) { return a + b; }
function add(a) { return a + 10; } // 覆蓋前者
add(1, 2); // 11(第二個版本,b=undefined → NaN,實際會出錯)
function add() {
if (arguments.length === 1) return arguments[0] + 10;
if (arguments.length === 2) return arguments[0] + arguments[1];
throw new Error('參數個數必須 1 或 2');
}
add(5); // 15
add(5, 10); // 15
// 缺點:arguments 非真數組、嚴格模式下受限、無法在箭頭函數中使用
function add(...args) {
switch (args.length) {
case 1: return args[0] + 10;
case 2: return args[0] + args[1];
default: throw new Error('參數個數必須 1 或 2');
}
}
// 類型重載:根據首參類型分發
function process(input) {
if (Array.isArray(input)) return input.map(x => x * 2);
if (typeof input === 'string') return input.toUpperCase();
if (typeof input === 'number') return input.toFixed(2);
throw new TypeError('不支援的類型');
}
process([1,2,3]); // [2,4,6]
process('hello'); // "HELLO"
process(3.14159); // "3.14"
// 單一配置對象替代多重載
function createUser(options = {}) {
const { name, age = 18, email, roles = ['user'] } = options;
if (!name) throw new Error('name 必填');
return { name, age, email, roles, id: Date.now() };
}
// 調用極其清晰
createUser({ name: 'Tom' });
createUser({ name: 'Jerry', age: 20, email: 'j@x.com' });
createUser({ name: 'Admin', roles: ['admin', 'user'] });
// 僅類型聲明,實現簽名需兼容所有重載
function format(value: string): string;
function format(value: number): string;
function format(value: Date): string;
function format(value: string | number | Date): string {
if (value instanceof Date) return value.toISOString();
return String(value);
}
// 使用
format('hello'); // string
format(123); // string
format(new Date()); // string
import { overloaded } from 'lodash/fp'; // 假設存在
// 手寫簡易版
function overload(...fns) {
return function(...args) {
for (const fn of fns) {
if (fn.length === args.length || fn.length === 0) { // 簡單匹配
try { return fn.apply(this, args); } catch { /* 忽略 */ }
}
}
throw new Error('No matching overload');
};
}
const add = overload(
(a) => a + 10,
(a, b) => a + b,
(a, b, c) => a + b + c
);
| 方案 | 執行效能 | 可讀性 | 類型安全 | 擴展性 | 推薦場景 |
|---|---|---|---|---|---|
| arguments + if/else | 中 | 低 | 無 | 差 | 極簡舊項目 |
| Rest + switch | 高 | 中 | 弱 | 中 | 參數個數重載 |
| 類型檢測分發 | 中 | 中 | 弱 | 中 | 參數類型重載 |
| 選項對象 | 高 | **高** | **強(TS)** | **強** | **通用首選** |
| TS 重載簽名 | 高 | 高 | **編譯時強** | 中 | TS 專案 API 設計 |
JS 無原生重載,**選項對象模式是工程實踐的最優解**:語義清晰、自動文檔化、支援預設值、TypeScript 友好、向後兼容。僅在極簡場景或庫作者需極致 API 簡潔時,使用 Rest 參數 + 類型/長度分發。TypeScript 專案請直接使用**重載簽名**獲得編譯時保護。