1. 参数默认值
1.1 基本用法
function greet(name) {
name = name || 'Guest';
return `Hello, ${name}!`;
}
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
console.log(greet());
console.log(greet('John'));
1.2 复杂默认值
function getDefaultName() {
return 'Guest_' + Date.now();
}
function greet(name = getDefaultName()) {
return `Hello, ${name}!`;
}
function createUser(
name = 'Guest',
age = 18,
email = `${name.toLowerCase()}@example.com`
) {
return { name, age, email };
}
2. rest 参数(剩余参数)
2.1 基本用法
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3));
console.log(sum(1, 2, 3, 4, 5));
function printInfo(title, ...items) {
console.log(title);
items.forEach(item => console.log(`- ${item}`));
}
printInfo('Shopping List', 'Apple', 'Banana', 'Orange');
2.2 实际应用场景
function handleEvent(eventName, ...handlers) {
handlers.forEach(handler => {
element.addEventListener(eventName, handler);
});
}
function buildURL(baseURL, ...params) {
const queryString = params
.map(param => `${param.key}=${param.value}`)
.join('&');
return `${baseURL}?${queryString}`;
}
function logger(level, ...messages) {
const timestamp = new Date().toISOString();
console.log(timestamp, level, ...messages);
}
3. name 属性
3.1 基本用法
function sayHello() {}
console.log(sayHello.name);
const sayBye = function() {};
console.log(sayBye.name);
const greet = () => {};
console.log(greet.name);
3.2 特殊情况
const boundFunction = sayHello.bind(null);
console.log(boundFunction.name);
const obj = {
sayHi() {}
};
console.log(obj.sayHi.name);
class Person {
constructor() {}
sayName() {}
}
console.log(new Person().sayName.name);
4. 箭头函数
4.1 基本语法
const add = (a, b) => a + b;
const double = x => x * 2;
const getTime = () => Date.now();
const calculate = (x, y) => {
const sum = x + y;
const product = x * y;
return { sum, product };
};
4.2 特性和限制
4.2.1 没有自己的 this
const counter = {
count: 0,
start: function() {
setInterval(function() {
this.count++;
}, 1000);
}
};
const counter = {
count: 0,
start: function() {
setInterval(() => {
this.count++;
}, 1000);
}
};
4.2.2 不能访问 arguments
function sum() {
return Array.from(arguments).reduce((a, b) => a + b, 0);
}
const sum = (...args) => args.reduce((a, b) => a + b, 0);
4.2.3 不能用作构造函数
function Person(name) {
this.name = name;
}
const person = new Person('John');
const Person = (name) => {
this.name = name;
};
const person = new Person('John');
4.3 实际应用场景
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(x => x * 2);
const evens = numbers.filter(x => x % 2 === 0);
fetchUser()
.then(user => fetchUserPosts(user.id))
.then(posts => processUserPosts(posts))
.catch(error => console.error(error));
const Button = ({ onClick, children }) => (
<button onClick={onClick}>
{children}
</button>
);
5. 最佳实践
5.1 何时使用箭头函数
const square = x => x * x;
elements.forEach(el => {
el.addEventListener('click', () => {
console.log('Clicked!');
});
});
const obj = {
name: 'John',
greet: () => {
console.log(this.name);
}
};
class Person {
name = 'John';
greet = () => {
console.log(this.name);
};
}
5.2 参数默认值最佳实践
function createUser({
name = 'Guest',
age = 18,
email = null
} = {}) {
return { name, age, email };
}
let counter = 0;
function increment(step = counter++) {}
function increment(step = 1) {
counter += step;
}