Files
front-end-example/03-javascript-core/09-scope-and-closure/starter.js
2026-03-19 15:17:29 +08:00

29 lines
663 B
JavaScript

function createCounter() {
let count = 0;
// 返回一个函数
function a() {
count++
return count
}
}
const counterA = createCounter()
const counterB = createCounter()
console.log(counterA());
console.log(counterA());
console.log(counterB());
// 任务:
// 1. 创建 counterA 和 counterB
// 2. 连续调用 counterA 两次
// 3. 再调用 counterB 一次
// 4. 观察为什么两个计数器互不影响
/*写一个 `createCounter` 函数
- 在函数内部定义 `count`
- 返回一个内部函数
- 每次调用内部函数时,`count` 都加 1
- 创建两个不同的计数器
- 观察为什么它们各自记住了自己的 `count`*/