模块 模式
一句话解释
模块 模式 uses 闭包 到 创建 私有 变量 and 公共 方法, encapsulating implementation details.
用大白话说
The module pattern is a design pattern that uses closures to create private state and controlled public access. Before native ES modules, it was the primary way to encapsulate code in JavaScript.
The pattern wraps code in an IIFE (Immediately Invoked Function Expression) that returns an object with only the public methods. Variables declared inside the IIFE are private — they cannot be accessed from outside, only through the returned methods.
Modern JavaScript uses ES modules (导入/导出) instead, which provide true file-level encapsulation. But the module pattern is still useful for creating singletons and understanding how closures enable data privacy.
示例
const counter = (function() {
let count = 0; // private
return {
increment() { count++; },
get() { return count; }
};
})();
counter.increment();
console.log(counter.get()); // 1 IIFE 创建 私有 数量 变量. 仅 increment and 获取 是 exposed.
相关术语
相关资源
相关课程
- 函数
学习 关于 模块 模式.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。