Node.js 函数
系统梳理 Node.js 函数的声明、表达式、箭头函数与四种调用方式,涵盖回调、Promise、async/await、闭包、高阶函数、参数解构及 HTTP 回调机制,并附 Node.js v24.22.3 实测结果。
学完这一章,你能够
- 系统梳理 Node.js 函数的声明、表达式、箭头函数与四种调用方式,涵盖回调、Promise、async/await、闭包、高阶函数、参数解构及 HTTP 回调机制,并附 Node.js v24.22.3 实测结果。
函数定位、定义形式与核心价值
函数是 JavaScript 与 Node.js 中封装可复用逻辑的基本单元,同时作为一等公民可以像普通值一样传递给其他函数,既可先命名再传入,也可在实参位置直接定义,这正是 Node.js 异步事件与回调模型的语言基石。
合理拆分函数能带来三项直接收益:通过代码复用消除重复逻辑、借助模块化将复杂业务拆解为职责清晰的小单元,以及显著提升调试定位与后续修改的可维护性。
定义函数主要有三种写法:`function` 关键字声明函数、将函数赋值给变量的函数表达式,以及 ES6 引入的简洁箭头函数(单表达式体可省略花括号与 `return`)。本站 Node.js v24.22.3 实测验证三类写法对输入 `'Alice'` 均返回 `'Hello, Alice!'`。
函数类型、异步演进与调用方式
按用途可区分普通函数(接收参数并返回结果)、匿名函数(无函数名,常直接传入 `setTimeout` 等接口)与回调函数(作为参数传入并在异步或特定步骤完成后触发)。
面对异步 I/O,工程上常将 `fs.readFile` 等回调接口封装为返回 `Promise` 的函数,再结合 `async`/`await` 与 `try...catch` 以同步风格编写异步流程。本站离线实测中,包装后的 `readFilePromise` 读出临时文件内容 `'node-async-ok'`,读取已删文件时捕获错误码 `'ENOENT'`;同时四种函数调用方式(直接调用、方法调用、构造函数调用、间接调用)对 `this` 绑定和实例创建的行为差异均已逐项验证,详见下方参考表。
闭包、高阶函数与现代参数处理
闭包让内部函数脱离外层词法作用域后仍能保持对局部状态(如计数器变量)的引用;高阶函数则接收函数作参数或返回新函数。本站实测闭包计数器连续调用返回 `[1, 2]`,`applyOperation(5, 3, op)` 分别传入加法与乘法箭头函数返回 `8` 与 `15`。
ES6 提供了三项高频参数特性:默认参数在未传实参时回退到默认值(实测无参返回 `'Hello, Guest!'`,传 `'Alice'` 返回 `'Hello, Alice!'`);剩余参数 `...numbers` 将不定长实参收集为数组(`sum(1, 2, 3, 4)` 实测为 `10`);解构参数直接从对象或数组提取字段(实测输出 `'Name: Alice, Age: 30'`)。
函数传递机制与 HTTP 服务器回调
编写业务函数时应坚持单一职责(如独立的 `calculateArea`)、避免依赖全局变量而改用局部变量与参数传入(如 `calculateTotal` 累加订单项)、在数组映射与回调中优先使用简洁箭头函数(如 `users.map(u => u.name)` 返回 `['Alice', 'Bob']`),并对异步失败路径统一用 `try...catch` 检查状态并处理异常。
把 `say` 作为参数传给 `execute(someFunction, value)` 时,传递的是函数引用本身而非调用返回值;在 `execute` 内部通过 `someFunction(value)` 执行并转发实参。若无需复用函数名,也可直接在实参位传入匿名函数 `function(word) { ... }`。
Node.js 的 `http.createServer` 正是基于这一函数传递机制:既可直接传入匿名请求处理回调,也可先定义具名函数 `onRequest(request, response)` 再传入 `createServer(onRequest)`。本站在本地回环 `127.0.0.1:0` 实测两种写法均返回 HTTP 200 与 `'Hello World'`。
设计原则、缓存优化与实战练习
日常编码应遵循四条函数设计原则:单一职责、采用“动词+名词”命名(如 `getUserInfo`)、控制单函数长度(建议不超过约 20 行)以及减少副作用以优先编写纯函数。性能层面可结合闭包与 `Map` 实现 `memoize(fn)` 结果缓存:本站实测重复计算 `cachedSquare(9)` 两次均返回 `81`,底层计算函数仅执行 `1` 次。
本章配套两道实战练习:其一实现摄氏度与华氏度互转函数 `convertTemperature(temp, unit)`(本站参考实现实测 `0°C -> 32°F`、`100°C -> 212°F`、`32°F -> 0°C`);其二封装包含 `on`、`emit`、`off` 方法的轻量 `EventEmitter` 类(实测触发一次后取消监听,后续 `emit` 不再回调)。
JavaScript / Node.js 四种函数调用方式对比
| 调用方式 | 调用示例 | 核心行为与 this 绑定 |
|---|---|---|
| 直接调用 | greet('Alice') | 最常见形式;严格模式与 ESM 下 this 为 undefined |
| 作为方法调用 | obj.method() | this 自动绑定为发起调用的宿主对象 obj |
| 构造函数调用 | new Constructor() | 创建新对象实例并将其绑定到构造函数内的 this |
| 间接调用 | greet.call(ctx, 'Bob') | 通过 call/apply 显式指定函数执行时的 this 上下文 |
运行 Node.js 函数定义、闭包、异步封装、HTTP 回调与实战练习实验
import http from 'node:http';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
function makeCase(name, expected, actual) {
return {
name,
passed: JSON.stringify(expected) === JSON.stringify(actual),
expected,
actual,
};
}
// Case 1: function declarations, expressions, arrows, and 4 invocation modes
function testFormsAndInvocation() {
function greetDecl(name) {
return `Hello, ${name}!`;
}
const greetExpr = function (name) {
return `Hello, ${name}!`;
};
const greetArrow = (name) => `Hello, ${name}!`;
const userObj = {
label: 'NodeObj',
method() {
return `this=${this.label}`;
},
};
function Box(value) {
this.value = value;
}
const box = new Box(42);
function describeRole(prefix) {
return `${prefix}:${this.role}`;
}
const indirect = describeRole.call({ role: 'admin' }, 'user');
const expected = {
decl: 'Hello, Alice!',
expr: 'Hello, Alice!',
arrow: 'Hello, Alice!',
methodThis: 'this=NodeObj',
ctorValue: 42,
ctorInstance: true,
indirect: 'user:admin',
};
const actual = {
decl: greetDecl('Alice'),
expr: greetExpr('Alice'),
arrow: greetArrow('Alice'),
methodThis: userObj.method(),
ctorValue: box.value,
ctorInstance: box instanceof Box,
indirect,
};
return makeCase('function_forms_and_invocation', expected, actual);
}
// Case 2: default/rest/destructured params, closures, higher-order functions, memoize
function testParamsClosuresAndHof() {
function greetDefault(name = 'Guest') {
return `Hello, ${name}!`;
}
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
function getUserInfo({ name, age }) {
return `Name: ${name}, Age: ${age}`;
}
function createCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
function applyOperation(a, b, operation) {
return operation(a, b);
}
function say(word) {
return `say:${word}`;
}
function execute(someFunction, value) {
return someFunction(value);
}
function calculateArea(width, height) {
return width * height;
}
function calculateTotal(items) {
let total = 0;
for (const item of items) {
total += item.price * item.quantity;
}
return total;
}
function memoize(fn) {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn(...args);
cache.set(key, result);
return result;
};
}
const counter = createCounter();
let computeCalls = 0;
const cachedSquare = memoize((n) => {
computeCalls += 1;
return n * n;
});
const sq1 = cachedSquare(9);
const sq2 = cachedSquare(9);
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
];
const expected = {
defaultUsed: 'Hello, Guest!',
defaultOverridden: 'Hello, Alice!',
restSum: 10,
destructured: 'Name: Alice, Age: 30',
closureSeq: [1, 2],
hofAdd: 8,
hofMul: 15,
namedPass: 'say:Hello',
anonPass: 'anon:Hello',
area: 24,
total: 50,
arrowMap: ['Alice', 'Bob'],
memoValues: [81, 81],
memoCalls: 1,
};
const actual = {
defaultUsed: greetDefault(),
defaultOverridden: greetDefault('Alice'),
restSum: sum(1, 2, 3, 4),
destructured: getUserInfo({ name: 'Alice', age: 30 }),
closureSeq: [counter(), counter()],
hofAdd: applyOperation(5, 3, (x, y) => x + y),
hofMul: applyOperation(5, 3, (x, y) => x * y),
namedPass: execute(say, 'Hello'),
anonPass: execute(function (word) {
return `anon:${word}`;
}, 'Hello'),
area: calculateArea(4, 6),
total: calculateTotal([
{ price: 10, quantity: 2 },
{ price: 15, quantity: 2 },
]),
arrowMap: users.map((u) => u.name),
memoValues: [sq1, sq2],
memoCalls: computeCalls,
};
return makeCase('params_closures_and_hof', expected, actual);
}
// Case 3: callback -> Promise wrapper and async/await try...catch
async function testAsyncPromiseAndError() {
const tmpFile = path.join(os.tmpdir(), `mbsky-fn-${process.pid}-${Date.now()}.txt`);
fs.writeFileSync(tmpFile, 'node-async-ok', 'utf8');
function readFilePromise(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
}
function callbackAsync(cb) {
setTimeout(() => cb('Some data'), 10);
}
const cbResult = await new Promise((resolve) => callbackAsync(resolve));
const okText = await readFilePromise(tmpFile);
fs.unlinkSync(tmpFile);
let caughtCode = null;
try {
await readFilePromise(tmpFile);
} catch (err) {
caughtCode = err.code;
}
const expected = {
cbResult: 'Some data',
okText: 'node-async-ok',
caughtCode: 'ENOENT',
};
const actual = { cbResult, okText, caughtCode };
return makeCase('async_promise_and_error_handling', expected, actual);
}
// Case 4: passing anonymous and named callbacks to http.createServer on 127.0.0.1:0
async function testHttpCallbackServer() {
async function probe(handler) {
const server = http.createServer(handler);
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
try {
const resp = await fetch(`http://127.0.0.1:${port}/`);
const text = await resp.text();
return { status: resp.status, text };
} finally {
await new Promise((resolve) => server.close(resolve));
}
}
const anonRes = await probe(function (request, response) {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.write('Hello World');
response.end();
});
function onRequest(request, response) {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.write('Hello World');
response.end();
}
const namedRes = await probe(onRequest);
const expected = {
anon: { status: 200, text: 'Hello World' },
named: { status: 200, text: 'Hello World' },
};
const actual = { anon: anonRes, named: namedRes };
return makeCase('http_callback_server', expected, actual);
}
// Case 5: chapter practice exercises (temperature conversion + simple EventEmitter)
function testPracticeExercises() {
function convertTemperature(temp, unit) {
if (unit === 'C') return Number(((temp * 9) / 5 + 32).toFixed(2));
if (unit === 'F') return Number((((temp - 32) * 5) / 9).toFixed(2));
throw new RangeError('Unit must be C or F');
}
class SimpleEventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
if (!this.events[event]) this.events[event] = [];
this.events[event].push(listener);
}
emit(event, ...args) {
for (const listener of this.events[event] || []) {
listener(...args);
}
}
off(event, listener) {
if (!this.events[event]) return;
this.events[event] = this.events[event].filter((fn) => fn !== listener);
}
}
const emitter = new SimpleEventEmitter();
const received = [];
const handler = (v) => received.push(v);
emitter.on('ping', handler);
emitter.emit('ping', 'first');
emitter.off('ping', handler);
emitter.emit('ping', 'second');
const expected = {
c0ToF: 32,
c100ToF: 212,
f32ToC: 0,
emitterEvents: ['first'],
};
const actual = {
c0ToF: convertTemperature(0, 'C'),
c100ToF: convertTemperature(100, 'C'),
f32ToC: convertTemperature(32, 'F'),
emitterEvents: received,
};
return makeCase('practice_exercises', expected, actual);
}
const cases = [
testFormsAndInvocation(),
testParamsClosuresAndHof(),
await testAsyncPromiseAndError(),
await testHttpCallbackServer(),
testPracticeExercises(),
];
console.log(JSON.stringify({ version: process.version, cases }));
- 核对四种调用方式、默认/剩余/解构参数、闭包计数器 [1,2]、memoize 命中 1 次调用、Promise 读文件与 ENOENT 捕获、本地 HTTP 匿名/具名回调 200 响应及两道实战练习。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
当前源码 SHA256:653295cdac5a7c5556dbc780a8d621090ea8bbcf306a33d399085ac09859909b
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
ZIP SHA256:b97e3ca5ab9acad4a73794e56a88df3fe1e7dd731a9076a19cab208457ea5412
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么向 http.createServer 传递 onRequest 时不能写成 http.createServer(onRequest())?
展开参考解答
加括号会立即执行 onRequest 并把其返回值(通常为 undefined)传给 createServer;不加括号才传递函数引用本身,供服务器在每次 HTTP 请求到达时回调执行。