Appearance
七、函数增强
ES6 对函数进行了多项增强,包括默认参数、rest 参数、箭头函数强化和函数参数解构等。
函数默认参数
基本用法
javascript
// 传统方式
function greet(name) {
name = name || 'Guest';
console.log(`Hello, ${name}!`);
}
// ES6 方式
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // Hello, Guest!
greet('John'); // Hello, John!复杂默认值
javascript
function createUser(name = 'Guest', age = 18, isAdmin = false) {
return {
name,
age,
isAdmin
};
}
console.log(createUser()); // { name: 'Guest', age: 18, isAdmin: false }
console.log(createUser('John', 30)); // { name: 'John', age: 30, isAdmin: false }
console.log(createUser('Jane', 25, true)); // { name: 'Jane', age: 25, isAdmin: true }表达式作为默认值
javascript
function getDate(date = new Date()) {
return date;
}
console.log(getDate()); // 当前日期
console.log(getDate(new Date('2023-01-01'))); // 2023-01-01
// 函数作为默认值
function lazyValue() {
console.log('Calculating...');
return 42;
}
function getValue(value = lazyValue()) {
return value;
}
console.log(getValue()); // 输出 "Calculating..." 然后输出 42
console.log(getValue(100)); // 直接输出 100,不调用 lazyValuerest 参数
基本用法
javascript
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15与普通参数结合
javascript
function greet(name, ...messages) {
console.log(`Hello, ${name}!`);
messages.forEach(message => console.log(message));
}
greet('John', 'How are you?', 'Welcome!');
// Hello, John!
// How are you?
// Welcome!替代 arguments
javascript
// 使用 arguments
function oldSum() {
return Array.from(arguments).reduce((acc, curr) => acc + curr, 0);
}
// 使用 rest 参数
function newSum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(oldSum(1, 2, 3)); // 6
console.log(newSum(1, 2, 3)); // 6箭头函数强化
简洁语法
javascript
// 传统函数
function add(a, b) {
return a + b;
}
// 箭头函数
const add = (a, b) => a + b;
console.log(add(1, 2)); // 3this 绑定
javascript
const obj = {
name: 'John',
greet: function() {
setTimeout(() => {
console.log(`Hello, ${this.name}!`);
}, 1000);
}
};
obj.greet(); // Hello, John!函数参数解构
对象参数解构
javascript
function config({ host = 'localhost', port = 3000, protocol = 'http' }) {
console.log(`Server running at ${protocol}://${host}:${port}`);
}
config({ host: 'example.com', port: 8080 }); // Server running at http://example.com:8080
config(); // Server running at http://localhost:3000数组参数解构
javascript
function coordinate([x, y]) {
console.log(`X: ${x}, Y: ${y}`);
}
coordinate([10, 20]); // X: 10, Y: 20混合使用
javascript
function complex({ name, age }, ...hobbies) {
console.log(`Name: ${name}, Age: ${age}`);
console.log(`Hobbies: ${hobbies.join(', ')}`);
}
complex({ name: 'John', age: 30 }, 'reading', 'coding', 'gaming');
// Name: John, Age: 30
// Hobbies: reading, coding, gaming函数增强的优势
- 代码简洁:默认参数减少了参数验证代码
- 可读性高:参数默认值和rest参数使函数签名更清晰
- 灵活性强:函数参数解构使参数传递更灵活
- this 绑定明确:箭头函数解决了 this 指向问题
通过本章节的学习,你已经掌握了 ES6 中函数的增强特性。这些特性可以使函数代码更简洁、更易读,提高开发效率。
