闭包实现安全私有计数器:通过外层函数封装 count 变量,仅暴露 increment、decrement、getValue 等方法操作它,外部无法直接访问或篡改;支持初始化参数与 Object.freeze 防结构修改。

用闭包实现安全的私有计数器,核心是把计数变量放在函数作用域内部,不暴露给外部,只通过返回的特定方法(如 increment、getValue)间接操作它。
闭包封装计数状态
定义一个外层函数(比如 createCounter),在其中声明一个局部变量(如 count)。这个变量不会被外部直接访问,但内层返回的函数能持续引用它——这就是闭包维持了对自由变量的访问权。
示例:
function createCounter() {
let count = 0; // 私有状态,外部无法直接读写
return {
increment() { count++; },
decrement() { count--; },
getValue() { return count; }
};
}
const counter = createCounter();
counter.increment();
console.log(counter.getValue()); // 1
console.log(counter.count); // undefined —— 安全,不可访问
防止外部篡改和意外覆盖
由于 count 是词法作用域内的局部变量,任何外部代码都无法赋值、删除或重新声明它。即使有人尝试在 counter 对象上添加 count 属性,也只是新增一个同名的自有属性,不会影响闭包内的原始 count。
立即学习“Java免费学习笔记(深入)”;
例如:
-
counter.count = 999→ 只是给对象加了一个新属性,counter.getValue()仍返回真实值 - 没有
eval、with或调试器介入的前提下,无法绕过作用域限制读取或修改count
支持初始化与配置(进阶用法)
可以扩展外层函数,接受初始值或步长等参数,让闭包更灵活:
function createCounter(initial = 0, step = 1) {
let count = initial;
return {
increment() { count += step; },
reset() { count = initial; },
getValue() { return count; }
};
}
const counter2 = createCounter(10, 2);
counter2.increment(); // 12
counter2.increment(); // 14
避免常见陷阱
注意不要在循环中错误地创建多个闭包却共享同一个变量;也不要返回箭头函数时误用 this(本例中无 this 依赖,所以安全)。另外,如果需要严格防篡改,可配合 Object.freeze 冻结返回的对象:
-
return Object.freeze({ increment, getValue })—— 防止新增/删除方法 - 但注意:这不能阻止闭包内变量被修改,只保护对象结构


















