JS 函数进阶
学习箭头函数、默认参数、rest参数 · 难度:进阶 · +15XP
JavaScript 函数进阶精讲
函数是 JavaScript 的一等公民(First-Class Citizen),这意味着函数可以被赋值给变量、作为参数传递、作为返回值返回。掌握函数的高级用法——箭头函数、默认参数、剩余参数、闭包、IIFE、高阶函数等——是深入 JavaScript 的核心。
箭头函数 (Arrow Function)
| 特性 | 普通函数 | 箭头函数 |
|---|---|---|
this 绑定 | 动态(调用时确定) | 词法(定义时确定) |
arguments 对象 | 有 | 无 |
| 构造函数能力 | 可用 new | 不能用作构造函数 |
prototype | 有 | 无 |
// 箭头函数语法
const add = (a, b) => a + b; // 单行隐式返回
const greet = name => "Hello " + name; // 单参数省略括号
const noArgs = () => "no args"; // 无参数用空括号
const complex = (a, b) => { // 多行需花括号 + return
const result = a * b;
return result * 2;
};
// this 绑定的关键区别
const user = {
name: "张三",
greetArrow: () => console.log("箭头: " + this.name), // this 指向外层作用域
greetFunc: function() { console.log("普通: " + this.name); } // this 指向 user
};
// user.greetArrow(); // undefined(this 是全局/window)
// user.greetFunc(); // "张三"
参数高级特性
- 默认参数:参数未传入或为 undefined 时使用默认值
- 剩余参数 (...rest):将剩余参数收集到一个数组中
- 参数解构:直接从参数中解构对象/数组
// 默认参数
function createUser(name, age = 18, role = "user") {
return { name, age, role };
}
console.log(createUser("小明")); // { name: "小明", age: 18, role: "user" }
// 剩余参数(替代 arguments)
function sum(...numbers) {
return numbers.reduce((acc, n) => acc + n, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15
// 参数解构
function printInfo({ name, age, city = "未知" }) {
console.log(name + ", " + age + "岁, " + city);
}
printInfo({ name: "张三", age: 25 }); // "张三, 25岁, 未知"
高阶函数与函数组合
// 高阶函数:接收或返回函数的函数
function withLogging(fn) {
return function(...args) {
console.log("调用参数:", args);
const result = fn.apply(this, args);
console.log("返回结果:", result);
return result;
};
}
// 函数组合(compose)
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const double = x => x * 2;
const addOne = x => x + 1;
const square = x => x * x;
const compute = compose(square, addOne, double);
console.log(compute(3)); // (3*2+1)^2 = 49
// IIFE (Immediately Invoked Function Expression)
(function() {
const privateVar = "我是私有变量";
console.log(privateVar); // 不污染全局作用域
})();