function box(num, a) { return num + a; }
function box(num) { return num; } // 覆蓋前一個
box(5, 11); // 55(只認最後定義)
box(5); // 5
JS 以**最後定義為準**,不支援依參數簽章多載。
function calculate() {
if (arguments.length === 2) return arguments[0] + arguments[1];
if (arguments.length === 3) return arguments[0] * arguments[1] * arguments[2];
throw new Error("參數數量不支援");
}
console.log(calculate(1, 2)); // 3
console.log(calculate(1, 2, 3)); // 6
缺點:`if/else` 膨脹、難維護、無型別檢查。
function createUser({ name, age = 18, role = "user" } = {}) {
return { name, age, role };
}
createUser({ name: "Alice" });
createUser({ name: "Bob", age: 25, role: "admin" });
優點:參數具名、順序不重要、預設值清晰、易擴充。
/**
* 多載分派器
* @param {Object} map - { "參數模式字串": 實作函式 }
* 參數模式:類型字母陣列,如 ["string", "number"] 或 "s,n"
* 支援 "?" 可選、 "..." 剩餘
*/
function overload(map) {
const entries = Object.entries(map).map(([pattern, fn]) => {
const types = pattern.split(",").map(s => s.trim());
return { types, fn };
});
return function (...args) {
for (const { types, fn } of entries) {
if (matchTypes(args, types)) return fn.apply(this, args);
}
throw new Error(`無匹配多載:${args.map(a => typeof a).join(",")}`);
};
}
function matchTypes(args, patterns) {
if (patterns.includes("...")) {
// 簡易處理:... 必須在最後
const restIdx = patterns.indexOf("...");
const fixed = patterns.slice(0, restIdx);
if (args.length < fixed.length) return false;
return fixed.every((t, i) => checkType(args[i], t));
}
if (args.length !== patterns.length) return false;
return patterns.every((t, i) => checkType(args[i], t));
}
function checkType(val, type) {
if (type.endsWith("?")) return val == null || checkType(val, type.slice(0, -1));
switch (type) {
case "s": case "string": return typeof val === "string";
case "n": case "number": return typeof val === "number";
case "b": case "boolean": return typeof val === "boolean";
case "f": case "function": return typeof val === "function";
case "o": case "object": return val !== null && typeof val === "object";
case "a": case "array": return Array.isArray(val);
case "*": return true;
default: return false;
}
}
// 使用
const process = overload({
"s,n": (name, age) => `姓名:${name}, 年齡:${age}`,
"s,n,?": (name, age, role) => `姓名:${name}, 年齡:${age}, 角色:${role || "user"}`,
"s,...": (name, ...tags) => `${name} 標籤: ${tags.join(",")}",
"o": (obj) => JSON.stringify(obj)
});
console.log(process("Alice", 20));
console.log(process("Bob", 25, "admin"));
console.log(process("Charlie", "js", "ts", "react"));
console.log(process({ a: 1 }));
function process(x: string, y: number): string;
function process(x: string, y: number, z?: string): string;
function process(x: object): string;
function process(...args: any[]): string {
// 實作同方案一或三
if (typeof args[0] === "object" && !Array.isArray(args[0])) return JSON.stringify(args[0]);
if (args.length === 2) return `姓名:${args[0]}, 年齡:${args[1]}`;
return `姓名:${args[0]}, 年齡:${args[1]}, 角色:${args[2] || "user"}`;
}
TypeScript 多載僅存在**型別檢查階段**,編譯後仍為單一函式,執行時仍需手動分派。
| 場景 | 推薦方案 |
|---|---|
| 參數少、型別固定、邏輯簡單 | arguments.length + if/else |
| 參數多、可選、需預設值、擴充性 | 選項物件 `{}` 解構 |
| 需依型別/數量分派完全不同邏輯 | 多載分派器 / TypeScript 多載簽章 |
| 庫/框架對外 API | TypeScript 多載 + JSDoc 文檔 |
**核心觀念**:JS 以「單一函式、內部分派」模擬多載。選項物件是最實用的現代模式;複雜分派時封裝 `overload` 輔助器保持乾淨。