JavaScript单例模式核心是确保多次调用始终返回同一实例引用,常用闭包缓存或ES6私有静态字段实现,单线程下天然线程安全,推荐直接导出实例以保证模块级唯一。
JavaScript 中实现单例模式的核心是:**控制构造函数只能返回同一个对象实例,且后续调用不再新建对象**。关键不在于“禁止 new 多次”,而在于“无论调用多少次,始终返回同一引用”。
这是最常用、最清晰的方式。利用立即执行函数(IIFE)封装私有变量,把实例存在闭包内,构造函数只负责检查并返回它:
示例:
const Singleton = (function() {
let instance = null;
function createInstance() {
return {
data: Math.random(),
getName() { return 'Singleton'; }
};
}
return {
getInstance() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
// 使用
const a = Singleton.getInstance();
const b = Singleton.getInstance();
console.log(a === b); // true
借助 #instance 私有字段和静态方法,语义更明确,避免全局污染:
示例:
class Logger {
#logHistory = [];
static #instance = null;
constr
uctor() {
if (Logger.#instance) {
return Logger.#instance;
}
Logger.#instance = this;
}
static getInstance() {
if (!Logger.#instance) {
Logger.#instance = new Logger();
}
return Logger.#instance;
}
log(msg) {
this.#logHistory.push(msg);
}
}
const l1 = Logger.getInstance();
const l2 = Logger.getInstance();
console.log(l1 === l2); // true
JavaScript 运行在单线程环境中,没有并发创建实例的风险。因此不需要模拟 Java 的双重检查锁(DCL)或 synchronized。上面两种方式在浏览器和 Node.js 中都天然线程安全。
更稳妥的做法是直接导出实例,彻底杜绝用户 new 的可能性:
示例(logger.js):
class Logger {
constructor() {
this.logs = [];
}
log(msg) {
this.logs.push(`[${Date.now()}] ${msg}`);
}
}
// ✅ 直接导出唯一实例
export default new Logger();
其他文件中:
import logger from './logger.js'; import logger2 from './logger.js'; console.log(logger === logger2); // true
不复杂但容易忽略:单例的关键不在“怎么写构造函数”,而在“怎么用”——统一通过 getInstance 或默认导出访问,才能真正保证唯一性。