在 ES6 (ES2015) 之前,JavaScript **不支援函數參數默認值** 直接寫在參數列表中。開發者必須在函數體內用邏輯或運算符手動實現。本文梳理從 ES5 到 ES6 的演進、各種寫法優缺點、陷阱與現代最佳實踐。
||) — 最常用,但有陷阱function openDiv(id, html, width, height) {
width = width || 500; // 寬度默認 500
height = height || 300; // 高度默認 300
// ...
}
// 呼叫
openDiv('myDiv', '<p>內容</p>'); // width=500, height=300
openDiv('myDiv', '<p>內容</p>', 800); // width=800, height=300
openDiv('myDiv', '<p>內容</p>', 0, 0); // ⚠️ 陷阱!0 是 falsy,實際變成 500, 300
缺點:0、''、false、null、undefined、NaN 都會觸發默認值,**無法傳遞「有意的假值」**。
undefined — 嚴格模式function openDiv(id, html, width, height) {
if (width === undefined) width = 500;
if (height === undefined) height = 300;
// ...
}
// 現在可以傳 0
openDiv('id', 'html', 0, 0); // width=0, height=0 ✅
優點:精準判斷「未傳遞」。
缺點:代碼冗長;arguments.length 檢查更繁瑣。
arguments.length 檢查 — 底層控制function openDiv(id, html, width, height) {
width = arguments.length > 2 ? width : 500;
height = arguments.length > 3 ? height : 300;
}
適用於需要區分「未傳遞」與「傳遞 undefined」的極罕見場景。
function openDiv(id, html, width = 500, height = 300) {
console.log(width, height);
}
// 呼叫
openDiv('id', 'html'); // 500 300
openDiv('id', 'html', 800); // 800 300
openDiv('id', 'html', 0, 0); // 0 0 ✅ 完美支援假值
openDiv('id', 'html', undefined, 400); // 500 400 (undefined 觸發默認值)
function({ a = 1, b = 2 } = {})arguments 仍反映實際傳入參數,不包含默認值 (非嚴格模式下映射行為複雜,建議嚴格模式)let counter = 0;
function foo(x = counter++) {
console.log(x);
}
foo(); // 0
foo(); // 1
foo(); // 2 (每次調用 counter++ 重新執行)
function createElement(tag = 'div', className = tag + '-wrapper') {
return { tag, className };
}
createElement(); // { tag: 'div', className: 'div-wrapper' }
createElement('span'); // { tag: 'span', className: 'span-wrapper' }
createElement('section', 'custom'); // { tag: 'section', className: 'custom' }
// 傳統選項物件
function ajax(options) {
options = options || {};
var method = options.method || 'GET';
var url = options.url || '/';
var data = options.data || null;
// ...
}
// ES6 解構 + 默認值 (清晰、可擴展、順序無關)
function ajax({ method = 'GET', url = '/', data = null, headers = {} } = {}) {
// 直接使用 method, url, data, headers
console.log(method, url, data, headers);
}
ajax(); // 全部默認
ajax({ url: '/api/users' }); // 僅覆蓋 url
ajax({ data: { id: 1 }, method: 'POST' });
function required(paramName) {
throw new Error('缺少必要參數: ' + paramName);
}
function createUser(name = required('name'), age = required('age')) {
return { name, age };
}
createUser('Tom'); // Error: 缺少必要參數: age
// ❌ 錯誤:所有調用共享同一個陣列/物件
function addItem(item, list = []) {
list.push(item);
return list;
}
addItem(1); // [1]
addItem(2); // [1, 2] 錯誤!預期 [2]
// ✅ 正確:默認值用 null,內部初始化
function addItem(item, list = null) {
if (list === null) list = [];
list.push(item);
return list;
}
addItem(1); // [1]
addItem(2); // [2] 正確
function greet(name: string = 'Guest', age: number = 18): string {
return `Hello ${name}, age ${age}`;
}
| 環境 | 支援 | 降級方案 |
|---|---|---|
| 現代瀏覽器 (Chrome 49+, Firefox 15+, Safari 10+, Edge 14+) | ✅ 完整支援 | 無需降級 |
| IE 11 | ❌ 不支援 | Babel 轉譯為 ES5 || 或 === undefined 邏輯 |
| Node.js | Node 6+ 完整支援 | 舊版本用 Babel |
// 源碼
function foo(a = 1, b = a + 1) { }
// Babel 轉譯 (ES5)
function foo(a, b) {
if (a === void 0) a = 1;
if (b === void 0) b = a + 1;
}
| 場景 | 推薦寫法 | 關鍵點 |
|---|---|---|
| 簡單函數、參數少、無假值需求 | param = param || default | 簡潔,但 0/''/false 會觸發默認值 |
| 通用函數、需支援假值 | param = default (ES6) | 標準、語義明確、惰性求值 |
| 參數超過 3-4 個、或未來擴展性 | 解構賦值 ({ a=1, b=2 } = {}) | 順序無關、自我文檔化、易擴展 |
| 必填參數 | param = required('name') | 運行時拋錯、文檔化 |
| 默認值為陣列/物件 | param = null; if (!param) param = [] | 避免共享引用 Bug |
JavaScript 默認參數從 ES5 的「手動邏輯判斷」進化為 ES6 的「聲明式語法糖」,背後是語言設計從**命令式**向**聲明式**的轉型。現代開發中:
掌握這些細節,能寫出更健壯、可讀、可維護的函數簽名。