【ES6新特性】默认参数常见用法
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