章节目录 · 8 章
JavaScript 教程 · 第 4 章
函数、作用域与闭包
函数是把一段代码取个名字、随时能调用的工具。JavaScript 里函数是一等公民(first-class citizen)——可以赋值给变量、作为参数传递、作为返回值,甚至可以拥有自己的属性。这让它能写出非常灵活的组合式代码。
本章会讲:
- 函数的三种写法和各自的坑
- 参数的各种高级用法
- 作用域三层模型与变量查找规则
- 闭包——JavaScript 最核心也最容易困惑的概念
- this 绑定与 call/apply/bind
一、函数的三种写法
// 方式 1:函数声明(有提升,整个作用域都可见)
function greet(name) {
return `你好,${name}!`;
}
// 方式 2:函数表达式 + const(现代项目推荐)
const add = function (a, b) {
return a + b;
};
// 方式 3:箭头函数(更短,无自己的 this 和 arguments)
const square = (x) => x * x; // 单参数,单表达式直接返回
const cube = x => x ** 3; // 单参数可以省略括号
const hello = (name) => { // 多语句需要大括号 + return
const msg = `Hello, ${name}`;
return msg;
};
const noArgs = () => "没有参数"; // 无参数必须写 ()
函数声明 vs 函数表达式:提升
// 函数声明会被"提升"到作用域顶部,所以在声明之前就可以调用
console.log(sum(1, 2)); // 3 ✅
function sum(a, b) {
return a + b;
}
// 函数表达式不会提升,只有声明那一行之后才能用
console.log(sub(3, 1)); // ❌ ReferenceError: Cannot access 'sub' before initialization
const sub = function (a, b) { return a - b; };
箭头函数 vs 普通函数的 5 个区别
| 特性 | 普通函数 | 箭头函数 |
|---|---|---|
| this 绑定 | 自己的 this,取决于调用方式 | 没有自己的 this,捕获外层的 |
| arguments 对象 | 有 arguments |
没有,用剩余参数 ...args |
| new 调用 | 可以当构造函数 | 不能,会报错 |
| prototype | 有 | 没有 |
| length | 形参个数 | 形参个数 |
// 区别 1:this
const person = {
name: "黄帝",
// 普通方法
normalMethod() {
console.log(this.name); // "黄帝" ← this 是 person
},
// 箭头方法(不常见,但可以写)
arrowMethod: () => {
console.log(this.name); // undefined ← this 是外层的(全局或 undefined)
}
};
// 区别 2:arguments
function normal() {
console.log(arguments); // [1, 2, 3]
}
const arrow = (...args) => {
// console.log(arguments); // ❌ ReferenceError
console.log(args); // [1, 2, 3] ← 用剩余参数代替
};
normal(1, 2, 3);
arrow(1, 2, 3);
// 区别 3:不能 new
const Car = () => {};
// new Car(); // ❌ TypeError: Car is not a constructor
什么时候用箭头函数?
- 写短回调时(map / filter / setTimeout),更短、更清晰
- 需要继承外层
this时(类方法里的 setTimeout、事件回调)
什么时候别用箭头函数?
- 定义对象方法时(
{ greet: () => {} }的 this 会错) - 定义类方法时(除非你确定不需要 this)
- 需要用
arguments时(用剩余参数替代)
二、参数的妙用
默认参数
// 没传 speed 时默认 1
function move(distance, speed = 1) {
return `移动 ${distance} 米,速度 ${speed} m/s`;
}
move(100); // 移动 100 米,速度 1 m/s
move(100, 5); // 移动 100 米,速度 5 m/s
// 默认值可以是表达式
function greet(name, greeting = `你好`) {
return `${greeting},${name}!`;
}
// 后面的参数可以引用前面的
function createUser(name, level = 1, tag = `Lv.${level}`) {
return { name, level, tag };
}
createUser("黄帝", 5); // { name: "黄帝", level: 5, tag: "Lv.5" }
// 默认值只在对应参数为 undefined 时生效(null 不算)
move(100, null); // "移动 100 米,速度 null m/s" ← null 不会触发默认值
move(100, undefined); // 正常触发默认值
剩余参数 ...
// 把多个参数收集成数组(必须放在最后)
function sum(...numbers) {
return numbers.reduce((acc, n) => acc + n, 0);
}
sum(1, 2, 3, 4); // 10
sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // 55
// 普通参数和剩余参数可以混用
function log(prefix, ...args) {
console.log(`[${prefix}]`, ...args);
}
log("INFO", "启动", "完成"); // [INFO] 启动 完成
// 替代旧的 arguments
function legacy() {
console.log(arguments[0], arguments[1]); // 不推荐
}
function modern(...args) {
console.log(args[0], args[1]); // 推荐
}
解构参数
// 参数是对象时,直接解构出来 + 默认值
function createUser({ name, age = 18, role = "user" } = {}) {
// = {} 防止没传参数时报错
return { name, age, role };
}
createUser({ name: "小明" }); // { name: "小明", age: 18, role: "user" }
createUser({ name: "小王", age: 25 }); // { name: "小王", age: 25, role: "user" }
createUser(); // { name: undefined, age: 18, role: "user" }
// 参数是数组时
function getFirstTwo([a, b]) {
return [a, b];
}
getFirstTwo([1, 2, 3, 4]); // [1, 2]
三、return 与多个返回值
// 多个值用对象打包(推荐,可以按名字取值)
function divide(a, b) {
const quotient = Math.floor(a / b);
const remainder = a % b;
return { quotient, remainder }; // 属性名和变量名相同时可以省略重名
}
const { quotient, remainder } = divide(17, 5);
console.log(quotient, remainder); // 3 2
// 或者用数组(按位置取值)
function minMax(arr) {
return [Math.min(...arr), Math.max(...arr)];
}
const [mn, mx] = minMax([3, 1, 4, 1, 5, 9]);
console.log(mn, mx); // 1 9
return 的一个小陷阱:
// ❌ 这样会报错
function bad() {
return
{
a: 1
};
}
// 实际等于 return; 然后 { a: 1 } 是死代码!
// 因为 JS 自动分号插入(ASI)在 return 后加了 ;
// ✅ 正确写法:大括号和 return 同行
function good() {
return {
a: 1
};
}
四、作用域:变量在哪里可见
JavaScript 有三种作用域:
| 作用域 | 边界 | 可见性 |
|---|---|---|
| 全局作用域 | 整个程序文件 | 顶层声明的 const / let / function 都在全局 |
| 函数作用域 | function 的 { } 内部 |
函数内声明的变量外部看不见 |
| 块级作用域 | if / for / { } 的 { } 内部 |
只有 let / const 支持,var 不支持 |
const outer = "外部"; // 全局作用域
if (true) {
const blockLet = "块内"; // 块级作用域
console.log(outer, blockLet); // 外部 块内
}
// console.log(blockLet); // ❌ ReferenceError
function test() {
const inside = "函数内"; // 函数作用域
console.log(outer, inside); // 外部 函数内
if (true) {
const innerBlock = "嵌套块";
console.log(inside, innerBlock); // 函数内 嵌套块
}
}
// console.log(inside); // ❌ ReferenceError
// var 没有块级作用域(历史遗留)
for (var i = 0; i < 3; i++) {}
console.log(i); // 3 ← var 泄漏到循环外了!
// let 有块级作用域
for (let j = 0; j < 3; j++) {}
// console.log(j); // ❌ ReferenceError
作用域链
当代码访问一个变量时,JS 引擎会从内向外一层层查找,直到找到为止。找到后就用它,不再往外找:
const x = "全局 x";
function level1() {
const x = "level1 的 x";
function level2() {
// 这里访问 x,会先找 level2 有没有 → 没有
// 再找 level1 → 有!"level1 的 x"
// 不会找到全局的 x
console.log(x); // "level1 的 x"
}
level2();
}
level1();
这就是作用域链:每个作用域都有一条指向外层作用域的链子。
遮蔽(Shadowing)
内层作用域声明了和外层同名的变量时,内层的会遮蔽外层的,外层的那个暂时不可访问:
const x = "外层";
function foo() {
const x = "内层"; // 遮蔽了外层
console.log(x); // "内层"
}
foo();
console.log(x); // "外层" ← foo 结束后内层的 x 没了
五、闭包:函数 + 它的作用域链
闭包是 JavaScript 最核心也最容易困惑的概念之一。定义:闭包是一个函数引用了它被创建时所在作用域里的变量,即使那个作用域已经结束。
例子:计数器
function makeCounter() {
let count = 0; // count 只存在于 makeCounter 调用期间
return function () { // 返回的函数"记住了" count 的位置
count += 1;
return count;
};
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
// 再创建一个,各自独立
const counter2 = makeCounter();
console.log(counter2()); // 1
console.log(counter()); // 4 ← counter 的 count 还是连续的
为什么 count 还活着? 因为返回的那个匿名函数内部引用了 count,JS 垃圾回收器发现"还有东西在用它",所以不会回收。
闭包的三大常见用途
1. 私有变量
// 用闭包实现"私有"数据,外部只能通过暴露的方法操作
function createBankAccount(initialBalance) {
let balance = initialBalance; // 外部无法直接访问
return {
deposit(amount) {
if (amount > 0) { balance += amount; }
},
withdraw(amount) {
if (amount > 0 && amount <= balance) { balance -= amount; }
},
getBalance() {
return balance;
}
};
}
const acc = createBankAccount(1000);
acc.deposit(500);
acc.withdraw(200);
console.log(acc.getBalance()); // 1300
// console.log(acc.balance); // undefined ← 直接访问不到
2. 工厂函数
// 批量生成相似的函数
function makeMultiplier(n) {
return (x) => x * n; // 返回的函数记住了 n
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
const half = makeMultiplier(0.5);
console.log(double(5)); // 10
console.log(triple(5)); // 15
console.log(half(5)); // 2.5
3. 回调函数记住当时的值
// 每个按钮的点击处理闭包自己的 index
for (let i = 0; i < 5; i++) {
const btn = document.createElement("button");
btn.textContent = `按钮 ${i}`;
btn.onclick = () => console.log(`点击了按钮 ${i}`); // 每个 btn 闭包自己的 i
document.body.appendChild(btn);
}
闭包的坑:循环里的 var
// ❌ 旧写法:所有 setTimeout 都拿到最终值 5
for (var i = 0; i < 5; i++) {
setTimeout(() => console.log(i), 100);
}
// 5 5 5 5 5 ← 所有回调共享同一个 i(因为 var 是函数级作用域)
// ✅ 现代写法:let 让每次循环的 i 都是独立的
for (let i = 0; i < 5; i++) {
setTimeout(() => console.log(i), 100);
}
// 0 1 2 3 4
// ✅ 旧写法的 hack:用 IIFE 创建独立作用域
for (var i = 0; i < 5; i++) {
(function (i) { // 传参进来,每次循环的 i 都是新的
setTimeout(() => console.log(i), 100);
})(i);
}
// 0 1 2 3 4
六、this:谁调用它,它就是谁
this 指向的是函数被调用时的那个对象(调用上下文),而不是函数被定义时的位置。这是 JS 新手最容易晕的点。
四种调用方式决定 this 指向
// 1. 对象方法调用 → this 是该对象
const obj = {
name: "黄帝",
greet() { console.log(this.name); }
};
obj.greet(); // "黄帝" ← this === obj
// 2. 普通函数调用(非严格模式)→ this 是全局对象(浏览器 window / Node global)
function standalone() {
console.log(this);
}
standalone(); // window(浏览器)或 global(Node)或 undefined(严格模式)
// 3. 普通函数调用(严格模式)→ this 是 undefined
"use strict";
function strictFn() { console.log(this); }
strictFn(); // undefined
// 4. new 调用 → this 是新创建的空对象
function User(name) {
this.name = name; // this = 新对象
}
const u = new User("黄帝"); // { name: "黄帝" }
方法回调丢失 this(经典坑)
const obj = {
name: "黄帝",
greet() { console.log(`你好,${this.name}`); }
};
// 把方法取出来当独立函数用 → this 丢失
const f = obj.greet;
f(); // 你好,undefined ← this 变成了全局对象,上面没有 name
// 传给回调也会丢失
setTimeout(obj.greet, 100); // 你好,undefined
// ❌ 临时解决办法
setTimeout(() => obj.greet(), 100); // 包一层箭头函数
// ❌ 或者用 bind
setTimeout(obj.greet.bind(obj), 100);
call / apply / bind:手动指定 this
const alice = { name: "Alice" };
const bob = { name: "Bob" };
function greet(greeting, punctuation) {
console.log(`${greeting},我是 ${this.name}${punctuation}`);
}
// call:立即调用,参数一个个传
greet.call(alice, "你好", "!"); // 你好,我是 Alice!
// apply:立即调用,参数数组传
greet.apply(bob, ["Hi", "."]); // Hi,我是 Bob.
// bind:返回一个绑定了 this 的新函数,不立即调用
const greetAlice = greet.bind(alice);
greetAlice("哈喽", "~"); // 哈喽,我是 Alice~
greetAlice("再见", "!"); // 再见,我是 Alice!
// bind 也能绑部分参数(柯里化)
const greetAliceHello = greet.bind(alice, "你好");
greetAliceHello("!"); // 你好,我是 Alice!
箭头函数没有自己的 this
// 箭头函数的 this 是定义时外层的 this,跟调用方式无关
const obj = {
name: "黄帝",
// 普通方法里的 setTimeout → this 丢失
normal() {
setTimeout(function () {
console.log(this.name); // undefined
}, 100);
},
// 箭头回调捕获外层 this → 正确
arrow() {
setTimeout(() => {
console.log(this.name); // "黄帝" ← 捕获了 obj
}, 100);
}
};
总结箭头函数的 this 规则:箭头函数不绑定自己的 this,它会沿着作用域链找到最近的一个非箭头函数的 this 来用。
七、递归
函数可以调用自己,这就是递归。递归通常需要两个要素:
- 基准情况(base case):什么时候停止递归
- 递归步骤:把问题缩小后再调自己
// 阶乘:n! = n * (n-1) * ... * 1
function factorial(n) {
if (n <= 1) return 1; // 基准情况
return n * factorial(n - 1); // 递归步骤
}
console.log(factorial(5)); // 120 (5*4*3*2*1)
// 斐波那契:F(n) = F(n-1) + F(n-2)
function fib(n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(10)); // 55
// 遍历嵌套数组
function flatten(arr) {
const result = [];
for (const item of arr) {
if (Array.isArray(item)) {
result.push(...flatten(item)); // 递归
} else {
result.push(item);
}
}
return result;
}
console.log(flatten([1, [2, [3, [4]], 5]])); // [1, 2, 3, 4, 5]
八、高阶函数
高阶函数是接受函数作为参数、或返回函数的函数。这是函数式编程的核心。
// 接受函数作为参数
function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}
repeat(3, (i) => console.log(`第 ${i + 1} 次`));
// 返回函数
function debounce(fn, delay) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
const onSearch = debounce((keyword) => {
console.log(`搜索:${keyword}`);
}, 300);
// 搜索框每次输入触发 onSearch,但 300ms 内连续输入只执行最后一次
九、练习
每道题都请自己先写,再对照参考答案。大部分练习题用 practice-04.js 运行即可(涉及浏览器 API 的 debounce/throttle 会在提示里说明)。
第 1 题:once 高阶函数(基础)
任务:实现一个 once(fn) 高阶函数,包装后 fn 只会执行一次。后面再调用直接返回第一次执行的结果。
const greet = once((name) => {
console.log("第一次被调用!");
return `你好,${name}!`;
});
console.log(greet("黄帝")); // 第一次被调用! / 你好,黄帝!
console.log(greet("小明")); // 你好,黄帝!(不会再次打印 "第一次被调用")
console.log(greet("小王")); // 你好,黄帝!
💡 提示:用闭包存两个变量——一个标记
hasCalled(是否执行过),一个存result(第一次的返回值)。第一次调用时执行 fn、存结果、标记 hasCalled;后续调用直接返回 result。还要注意this绑定和参数透传。
✅ 参考答案:
function once(fn) { let hasCalled = false; let result; return function (...args) { if (!hasCalled) { // 第一次:执行原函数,存结果 result = fn.apply(this, args); // 用 apply 保持 this 正确 hasCalled = true; } return result; // 后续直接返回缓存结果 }; } // 测试 const greet = once((name) => { console.log("第一次被调用!"); return `你好,${name}!`; }); console.log(greet("黄帝")); // 第一次被调用! 你好,黄帝! console.log(greet("小明")); // 你好,黄帝! console.log(greet("小王")); // 你好,黄帝! // 实际场景:初始化函数只跑一次 const initApp = once(() => { console.log("应用初始化中...(只执行一次)"); return { started: true, timestamp: Date.now() }; }); initApp(); // 应用初始化中...(只执行一次) initApp(); // (不打印任何东西,直接返回第一次的结果)
第 2 题:memoize 缓存函数(核心)
任务:实现一个 memoize(fn) 高阶函数,缓存 fn 的计算结果。相同参数再次调用时直接返回缓存,不再重新计算。
然后用它包装一个计算斐波那契的慢版本,对比 memoize 前后的性能差异。
// 未优化:指数级复杂度,n=35 就已经慢了
function fibSlow(n) {
if (n < 2) return n;
return fibSlow(n - 1) + fibSlow(n - 2);
}
💡 提示:闭包里存一个
Map或者普通对象作为缓存表。每次调用时,把参数(用 JSON.stringify 拼成 key)查一下缓存里有没有,有就直接返回,没有就计算并存入缓存。注意:如果 fn 接受多个参数或对象参数,key 的生成要能区分不同输入。
✅ 参考答案:
function memoize(fn) { const cache = new Map(); // 用 Map 比普通对象更好,支持任意类型的 key return function (...args) { // 用 JSON.stringify 把参数序列化成唯一 key const key = JSON.stringify(args); if (cache.has(key)) { console.log(`[缓存命中] 参数: ${key}`); return cache.get(key); } const result = fn.apply(this, args); cache.set(key, result); console.log(`[首次计算] 参数: ${key} = ${result}`); return result; }; } // 慢版本斐波那契 function fibSlow(n) { if (n < 2) return n; return fibSlow(n - 1) + fibSlow(n - 2); } // 包装后的版本 const fibMemo = memoize(fibSlow); // 测试(第一次:逐个子问题都首次计算) console.time("memo fib(20)"); console.log("fib(20) =", fibMemo(20)); console.timeEnd("memo fib(20)"); // 第二次:全部命中缓存 console.time("再次调用 fib(20)"); console.log("fib(20) =", fibMemo(20)); console.timeEnd("再次调用 fib(20)"); /* 输出对比: 第一次:会打印很多 [首次计算](每个子问题都算一遍) 第二次:直接 [缓存命中],几乎 0ms */ // 也可以用普通对象做 key,但要注意: // 普通对象的 key 只能是字符串/number,JSON.stringify 正好统一转成字符串
第 3 题:防抖 debounce + 节流 throttle(进阶)
任务:分别实现 debounce(fn, delay) 和 throttle(fn, interval) 两个高阶函数,理解它们的区别和适用场景。
- debounce:事件停止触发 delay 毫秒后才执行(适用于搜索框输入联想、窗口 resize 后重排等场景)
- throttle:每隔 interval 毫秒最多执行一次(适用于滚动条位置更新、高频点击按钮等场景)
在 浏览器 里用下面的 HTML 测试你的实现(Node.js 里没有 scroll/input 事件):
<!DOCTYPE html>
<html>
<head>
<title>Debounce / Throttle 测试</title>
<style>body { font-family: sans-serif; padding: 20px; }
#log { height: 300px; overflow: auto; border: 1px solid #ccc; padding: 10px; }</style>
</head>
<body>
<input id="search" placeholder="快速输入试试 debounce...">
<div id="log"></div>
<script src="debounce-throttle.js"></script>
</body>
</html>
💡 提示:
- debounce:用
setTimeout,每次触发都先clearTimeout再setTimeout,所以连续触发只会执行最后一次- throttle:用一个标记
lastTime,每次触发时判断"距离上次执行是否超过 interval",没超过就跳过,超过了才执行并更新 lastTime
✅ 参考答案:
debounce-throttle.js:// debounce:防抖,delay 毫秒内连续触发只执行最后一次 function debounce(fn, delay) { let timer = null; return function (...args) { const context = this; clearTimeout(timer); // 每次先清掉之前的定时器 timer = setTimeout(() => { fn.apply(context, args); }, delay); }; } // throttle:节流,interval 毫秒内最多执行一次 function throttle(fn, interval) { let lastTime = 0; return function (...args) { const now = Date.now(); if (now - lastTime >= interval) { lastTime = now; fn.apply(this, args); } }; } // ---- 浏览器测试代码 ---- const log = (msg) => { const el = document.getElementById("log"); const div = document.createElement("div"); div.textContent = `${new Date().toLocaleTimeString()} - ${msg}`; el.appendChild(div); el.scrollTop = el.scrollHeight; }; // 防抖测试:搜索框输入(停 300ms 才触发搜索) const searchInput = document.getElementById("search"); const onSearch = debounce((e) => { log(`🔍 搜索:${e.target.value}`); }, 300); searchInput.addEventListener("input", onSearch); // 节流测试:窗口滚动事件(每 200ms 最多触发一次) const onScroll = throttle(() => { log(`📜 滚动位置:${window.scrollY}`); }, 200); window.addEventListener("scroll", onScroll); /* 手动测试建议: 1. 在搜索框里快速连续输入多个字符 → 观察 debounce 只在你停下来 300ms 后触发一次 2. 上下滚动页面 → 观察 throttle 大概每 200ms 才输出一次 debounce 和 throttle 的核心区别: - debounce:等你停下来,才执行一次("懒加载"思想) - throttle:不管你怎么快,我固定频率执行("定时批处理"思想) */
第 4 题:递归 flatten 嵌套数组(进阶)
任务:实现一个递归函数 flattenDeep(arr, depth = Infinity),把任意深度的嵌套数组展开成一层。可选参数 depth 控制展开的深度(默认全部展开)。
flattenDeep([1, [2, [3, [4]], 5]]); // [1, 2, 3, 4, 5]
flattenDeep([1, [2, [3, [4]], 5]], 1); // [1, 2, [3, [4]], 5] ← 只展开一层
flattenDeep([1, [2, [3, [4]], 5]], 2); // [1, 2, 3, [4], 5] ← 展开两层
flattenDeep([1, 2, 3]); // [1, 2, 3]
flattenDeep([]); // []
💡 提示:递归函数的两个要素——基准情况(什么时候停止)和递归步骤。遍历数组每个元素,如果元素是数组且 depth > 0,就递归调用 flattenDeep(depth - 1),然后把结果用展开运算符
...push 进结果数组;如果不是数组或 depth 耗尽,直接 push。
✅ 参考答案:
function flattenDeep(arr, depth = Infinity) { const result = []; for (const item of arr) { if (Array.isArray(item) && depth > 0) { // 递归:depth 减 1,展开结果用 ... 加入 result result.push(...flattenDeep(item, depth - 1)); } else { // 基准情况:不是数组或 depth 耗尽,直接加入 result.push(item); } } return result; } // 测试 console.log(flattenDeep([1, [2, [3, [4]], 5]])); // [1, 2, 3, 4, 5] console.log(flattenDeep([1, [2, [3, [4]], 5]], 1)); // [1, 2, [3, [4]], 5] console.log(flattenDeep([1, [2, [3, [4]], 5]], 2)); // [1, 2, 3, [4], 5] console.log(flattenDeep([1, 2, 3])); // [1, 2, 3] console.log(flattenDeep([])); // [] // 对比原生方法(只展开一层): console.log([1, [2, [3]]].flat()); // [1, 2, [3]] console.log([1, [2, [3]]].flat(2)); // [1, 2, 3] console.log([1, [2, [3]]].flat(Infinity)); // [1, 2, 3]
第 5 题:call / apply / bind 实战(核心)
任务:理解这三个方法的区别,并分别用它们解决下面的问题:
问题 1:用 Math.max 找出数组最大值——但 Math.max(...arr) 虽然好用,它是 ES6 之前不支持的写法。请用 apply 实现一个兼容的版本 myMax(arr)。
问题 2:有一个简化版的"日志函数",支持不同前缀。用 bind 预绑定不同前缀,创建 logInfo、logWarn、logError 三个函数。
问题 3:解释下面代码中 this 的指向变化,以及如何用 call 或箭头函数修复。
const obj = {
name: "黄帝",
sayHello: function () {
console.log(`你好,我是 ${this.name}`);
},
setNameTimeout: function () {
setTimeout(function () {
console.log(`this.name 现在是: ${this.name}`); // ❌ 这里 this 是什么?
}, 100);
}
};
💡 提示:
apply的魅力在于它接受参数数组,能把数组展开传进函数(虽然 ES6 展开运算符更现代)bind返回一个新函数,可以预绑定this和部分参数(柯里化)- setTimeout 里的普通函数会丢失 this,
this.name变成 undefined;修复方法有三:箭头函数、bind、或者在外层存const self = this
✅ 参考答案:
// 问题 1:用 apply 求数组最大值 function myMax(arr) { // apply 接受 [thisArg, argsArray] // Math.max 不依赖 this,所以第一个参数随便传 return Math.max.apply(null, arr); } console.log(myMax([3, 1, 4, 1, 5, 9, 2, 6])); // 9 // 现代写法:Math.max(...arr) 是 ES6 展开运算符,apply 是旧时代的等价物 // 问题 2:bind 预绑定前缀 function logger(prefix, msg) { console.log(`[${prefix}] ${msg}`); } // 用 bind 预绑第一个参数 const logInfo = logger.bind(null, "INFO"); const logWarn = logger.bind(null, "WARN"); const logError = logger.bind(null, "ERROR"); logInfo("服务启动"); // [INFO] 服务启动 logWarn("磁盘空间不足"); // [WARN] 磁盘空间不足 logError("连接超时"); // [ERROR] 连接超时 // 问题 3:setTimeout 里的 this 丢失 const obj = { name: "黄帝", sayHello: function () { console.log(`你好,我是 ${this.name}`); }, setNameTimeout: function () { // ❌ 原写法:普通函数的 this 是 setTimeout 的调用上下文(全局对象) setTimeout(function () { console.log(`this.name 现在是: ${this.name}`); // undefined(浏览器)或 undefined(严格模式) }, 100); // ✅ 修复 1:箭头函数(继承外层 this) setTimeout(() => { console.log(`修复1 - this.name: ${this.name}`); // "黄帝" }, 100); // ✅ 修复 2:call/bind 显式绑定 setTimeout(function () { console.log(`修复2 - this.name: ${this.name}`); // "黄帝" }.bind(this), 100); // ✅ 修复 3:外层存 self const self = this; setTimeout(function () { console.log(`修复3 - self.name: ${self.name}`); // "黄帝" }, 100); } }; obj.setNameTimeout();
第 6 题:闭包实现私有变量计数器(综合)
任务:用闭包实现一个完整的 createCounter(options) 工厂函数,创建的计数器对象要有以下能力:
const counter = createCounter({
initial: 10, // 初始值(默认 0)
step: 2, // 步长(默认 1)
min: 0, // 最小值(默认无限制)
max: 100 // 最大值(默认无限制)
});
counter.inc(); // + step,返回新值(12)
counter.inc(); // 14
counter.dec(); // - step,返回新值(12)
counter.reset(); // 重置为 initial,返回新值(10)
counter.get(); // 只返回当前值(10)
// 边界:到达 min/max 时自动 clamp
const c2 = createCounter({ initial: 0, step: 10, min: 0, max: 30 });
c2.inc(); // 10
c2.inc(); // 20
c2.inc(); // 30
c2.inc(); // 30 ← 到达 max,不再增加
c2.dec(); // 20
// 关键:外部无法直接修改内部的 _count
// counter._count = 999; // 不会影响真正的内部状态
// counter.get(); // 还是 10
💡 提示:闭包的核心是"函数引用了外部作用域的变量",即使外部函数已经返回。在
createCounter内部声明let _count和_options,然后返回一个对象,对象的每个方法都通过闭包访问和修改_count。这样_count只有返回的对象的方法能操作,外部代码碰不到。
✅ 参考答案:
function createCounter(options = {}) { // 解构参数 + 默认值 const { initial = 0, step = 1, min = -Infinity, max = Infinity } = options; // 闭包里的私有变量:外部直接访问不到 let _count = initial; // 内部辅助函数(也是私有的) function clamp(val) { return Math.min(Math.max(val, min), max); } // 返回的对象,每个方法都闭包了 _count return { inc() { _count = clamp(_count + step); return _count; }, dec() { _count = clamp(_count - step); return _count; }, reset() { _count = initial; return _count; }, get() { return _count; } }; } // 测试 1:基本功能 const counter = createCounter({ initial: 10, step: 2, min: 0, max: 100 }); console.log(counter.inc()); // 12 console.log(counter.inc()); // 14 console.log(counter.dec()); // 12 console.log(counter.reset()); // 10 console.log(counter.get()); // 10 // 测试 2:边界 clamp const c2 = createCounter({ initial: 0, step: 10, min: 0, max: 30 }); c2.inc(); // 10 c2.inc(); // 20 c2.inc(); // 30 c2.inc(); // 30(到达 max,被 clamp 住) c2.dec(); // 20 // 测试 3:真的是私有变量 counter._count = 999; // 外部强行赋值 console.log(counter.get()); // 10(内部闭包的 _count 不受影响!) // 测试 4:每个计数器互相独立 const a = createCounter({ initial: 5 }); const b = createCounter({ initial: 5 }); a.inc(); // 6 b.inc(); // 6(互不干扰)
小结
- 三种写法:函数声明(有提升)、函数表达式 + const(推荐)、箭头函数(短、无 this)。
- 参数支持默认值、剩余参数 ...args、解构参数。
- 作用域三层:全局 / 函数 / 块级(只有 let/const 支持块级)。
- 闭包 = 函数 + 它被创建时的作用域;常用于私有变量、工厂函数、循环回调。
- this 取决于调用方式:方法调用是对象、普通调用是全局、new 是新对象、call/apply/bind 手动指定。
- 箭头函数没有自己的 this 和 arguments,会捕获外层的。
- 高阶函数(接受/返回函数)和递归是函数式编程的两大武器。
更多JavaScript教程:https://hc8.top/html-js/index.html