JavaScript中闭包是最经典私有变量封装手段,通过IIFE、构造函数+闭包、模块模式实现私有状态;ES6后WeakMap可配合class实现更健壮的私有存储。

JavaScript 中没有原生的私有字段语法(ES2022 前),闭包是最经典、最可靠的私有变量封装手段。它利用函数作用域链,让外部无法直接访问内部变量,只通过返回的特定函数间接操作。
基础闭包封装模式
通过立即执行函数(IIFE)创建独立作用域,将变量定义在内部,仅暴露有限接口:
const Counter = (function() {
let count = 0; // 私有变量,外部不可访问
return {
increment: () => ++count,
decrement: () => --count,
getCount: () => count,
reset: () => { count = 0; }
};
})();
console.log(Counter.getCount()); // 0
Counter.increment();
console.log(Counter.getCount()); // 1
console.log(Counter.count); // undefined —— 无法直接访问
构造函数 + 闭包(实例级私有)
每个实例拥有独立的私有状态,适合需要多个对象且互不干扰的场景:
function createPerson(name, age) {
// 每个实例独有的私有数据
let _name = name;
let _age = age;
return {
getName: () => _name,
getAge: () => _age,
setAge: (newAge) => {
if (newAge > 0) _age = newAge;
},
introduce: () => `I'm ${_name} and ${_age} years old.`
};
}
const alice = createPerson("Alice", 30);
const bob = createPerson("Bob", 25);
console.log(alice.introduce()); // I'm Alice and 30 years old.
console.log(bob.introduce()); // I'm Bob and 25 years old.
// alice._name 和 bob._name 彼此隔离,互不影响
模块模式:支持私有方法与初始化逻辑
在封装变量的同时,可定义仅内部调用的辅助函数,增强内聚性与可维护性:
const BankAccount = (function() {
// 私有工具函数
const isValidAmount = (amt) => typeof amt === 'number' && amt >= 0;
// 私有状态
let balance = 0;
const transactions = [];
return {
deposit: (amt) => {
if (isValidAmount(amt)) {
balance += amt;
transactions.push({ type: 'deposit', amount: amt });
}
},
withdraw: (amt) => {
if (isValidAmount(amt) && amt balance,
getHistory: () => [...transactions] // 返回副本,避免外部篡改
};
})();
现代补充:WeakMap 实现更健壮的私有存储(ES6+)
当需与 class 配合使用,或希望私有数据不被 JSON.stringify 泄露时,WeakMap 是更优选择:
const privateData = new WeakMap();
class User {
constructor(name, email) {
// 私有字段存于 WeakMap,键为 this 实例
privateData.set(this, { name, email, _lastLogin: null });
Object.defineProperty(this, 'name', {
get: () => privateData.get(this).name,
set: (val) => { privateData.get(this).name = val; }
});
}
login() {
privateData.get(this)._lastLogin = new Date();
}
getLastLogin() {
return privateData.get(this)._lastLogin;
}
}
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











