萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 函數默認參數:從 ES5 邏輯或寫法到 ES6 原生語法的演進與最佳實踐

前言

在 ES6 (ES2015) 之前,JavaScript **不支援函數參數默認值** 直接寫在參數列表中。開發者必須在函數體內用邏輯或運算符手動實現。本文梳理從 ES5 到 ES6 的演進、各種寫法優缺點、陷阱與現代最佳實踐。

一、ES5 時代的三種主流寫法

1. 邏輯或 (||) — 最常用,但有陷阱

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 都會觸發默認值,**無法傳遞「有意的假值」**。

2. 判斷 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 檢查更繁瑣。

3. arguments.length 檢查 — 底層控制

function openDiv(id, html, width, height) {
    width = arguments.length > 2 ? width : 500;
    height = arguments.length > 3 ? height : 300;
}

適用於需要區分「未傳遞」與「傳遞 undefined」的極罕見場景。

二、ES6 原生默認參數 (標準化、語法糖)

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 解耦: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' }

三、進階模式與最佳實踐

1. 物件解構默認值 (選項物件模式) — 參數多時首選

// 傳統選項物件
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' });

2. 必填參數強制檢查

function required(paramName) {
    throw new Error('缺少必要參數: ' + paramName);
}

function createUser(name = required('name'), age = required('age')) {
    return { name, age };
}
createUser('Tom'); // Error: 缺少必要參數: age

3. 避免可變默認值共享引用 (經典坑)

// ❌ 錯誤:所有調用共享同一個陣列/物件
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] 正確

4. 結合 TypeScript 類型註解

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.jsNode 6+ 完整支援舊版本用 Babel

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 的「聲明式語法糖」,背後是語言設計從**命令式**向**聲明式**的轉型。現代開發中:

  1. 新專案全面使用 ES6 默認參數 (配合 Babel 兼容舊環境)
  2. 參數 > 3 個改用解構賦值選項物件
  3. 警惕可變默認值共享引用陷阱
  4. 善用惰性求值特性 實現計數器、工廠函數等進階模式

掌握這些細節,能寫出更健壯、可讀、可維護的函數簽名。

copyright © 萬盛學電腦網 all rights reserved