JavaScript 函数是被设计为执行特定任务的代码块。
JavaScript 函数会在某代码调用它时被执行。
一、函数核心概念
1.定义方式:
javascript
// 1. 函数声明(提升机制)
function sum(a, b) {
return a + b;
}
// 2. 函数表达式
const multiply = function(a, b) {
return a * b;
};
// 3. 箭头函数(ES6+)
const divide = (a, b) => a / b;
2.执行上下文(this):
- 普通函数:动态绑定(取决于调用方式)
javascript
const obj = {
value: 10,
getValue: function() {
return this.value; // this = obj
}
};
- 箭头函数:静态绑定(定义时确定,继承父作用域)
javascript
const obj = {
value: 10,
getValue: () => this.value // this = window (非严格模式)
};
二、高级函数特性
1.闭包(Closure):
javascript
function createCounter() {
let count = 0; // 私有变量
return function() {
return ++count;
};
}
const counter = createCounter();
counter(); // 1
counter(); // 2
-
应用场景:
-
模块模式(封装私有变量)
-
防抖/节流函数
-
函数柯里化
-
2.高阶函数(HOF):
javascript
// 接受函数作为参数
function transformArray(arr, mapper) {
return arr.map(mapper);
}
// 返回函数
function createMultiplier(factor) {
return (x) => x * factor;
}
const double = createMultiplier(2);
三、函数参数处理
特性 | 示例 | 说明 |
---|---|---|
默认参数 | (x = 10) => x |
ES6 参数默认值 |
Rest 参数 | (...args) => args.length |
接收剩余参数为数组 |
解构参数 | ({ id, name }) => id |
对象/数组解构传参 |
四、异步函数模式
1.回调函数(Callback):
javascript
fetchData(url, (data, error) => {
if (error) handleError(error);
else processData(data);
});
2.Promise + async/await:
javascript
async function loadData() {
try {
const res = await fetch('/api/data');
const data = await res.json();
return data;
} catch (error) {
console.error("Fetch failed:", error);
}
}
五、最佳实践与性能
1.优化技巧:
-
避免嵌套过深(使用 Promise 链式调用)
-
惰性函数:运行时重写自身
javascript
function getViewportWidth() {
const width = window.innerWidth;
getViewportWidth = () => width; // 后续调用直接返回缓存值
return width;
}
2.内存管理:
-
解除事件监听防止内存泄漏
-
避免闭包滥用导致变量无法回收
六、函数式编程实践
1.纯函数原则:
javascript
// 纯函数 (无副作用)
const pureAdd = (a, b) => a + b;
// 非纯函数
let counter = 0;
const impureAdd = (x) => counter += x;
2.常用工具:
javascript
// 柯里化
const curry = (fn) =>
(a) => (b) => fn(a, b);
// 函数组合
const compose = (...fns) =>
(x) => fns.reduceRight((v, f) => f(v), x);
七、调试与错误处理
1.堆栈追踪:
- 命名函数表达式更易调试:
javascript
const calculate = function calc(a, b) {
// 调试时显示 calc 而非 anonymous
};
2.错误边界:
javascript
function safeParse(json) {
try {
return JSON.parse(json);
} catch (e) {
return { error: "Invalid JSON" };
}
}
总结:函数在现代前端中的角色
-
组件逻辑封装:React/Vue 组件本质是函数
-
状态管理:Redux reducer 必须是纯函数
-
异步流程控制:Promise/async 处理数据流
-
工具库构建:Lodash/Ramda 的函数式工具