ES6新特性之默認參數的多種用法
🚀默認參數基礎用法
在ES6中,我們可以直接在函數參數列表中為參數設置默認值:
// ES5的實現方式
function greet(name) {name = name || 'Guest';console.log(`Hello, ${name}!`);
}// ES6默認參數寫法
function greet(name = 'Guest') {console.log(`Hello, ${name}!`);
}greet(); // Hello, Guest!
greet('Alice'); // Hello, Alice!
特性說明:
- 默認值僅在參數為
undefined
時生效 null
會被認為是一個有效值,不會觸發默認值- 默認參數可以是任意表達式
🚀默認參數的進階用法
1. 結合解構賦值
// 對象解構默認值
function setOptions({ width = 100, height = 200, color = '#fff'
} = {}) {console.log(width, height, color);
}setOptions({ width: 500 }); // 500 200 #fff
setOptions(); // 100 200 #fff// 數組解構默認值
function getFirst([firstItem = 0] = []) {return firstItem;
}
2. 后置參數默認值
function createElement(tag = 'div', content) {const elem = document.createElement(tag);elem.textContent = content;return elem;
}// 必須顯式傳遞undefined才能使用默認值
const div = createElement(undefined, 'Hello');
3. 動態默認值
function generateId(prefix = 'id', random = Math.random().toString(36).slice(2)) {return `${prefix}_${random}`;
}console.log(generateId()); // id_1a2b3c
console.log(generateId('user')); // user_4d5e6f
🚀默認參數的作用域
1. 參數順序依賴
function tricky(a = 1, b = a * 2) {console.log(a, b);
}tricky(); // 1 2
tricky(3); // 3 6
tricky(2, 4); // 2 4
2. 暫時性死區(TDZ)
function example(a = b, b = 2) {// ? 錯誤:Cannot access 'b' before initialization
}function validExample(a = 2, b = a * 3) {// ? 正確
}
🚀實際應用場景
1. 配置項合并
function initPlugin(options = {}) {const defaults = {debug: false,maxRetry: 3,timeout: 5000};return { ...defaults, ...options };
}
2. API請求參數處理
async function fetchData({url = '/api/data',method = 'GET',headers = { 'Content-Type': 'application/json' }
} = {}) {try {const response = await fetch(url, { method, headers });return response.json();} catch (error) {console.error('Request failed:', error);}
}
🚀注意事項
- 箭頭函數的默認參數:
const multiply = (a = 1, b = 1) => a * b;
- 默認參數不計入函數length屬性:
function demo(a, b = 1, c) {}
console.log(demo.length); // 1
- 默認值表達式在每次調用時重新計算:
function getTime(now = Date.now()) {return now;
}console.log(getTime() === getTime()); // false