JavaScript单例模式核心是确保类唯一实例并提供全局访问点,主要实现方式有闭包+IIFE(兼容性好)、ES6 class+静态属性(语义清晰)、模块模式(天然单例、最自然)及带参懒加载变体,选择取决于项目兼容性、规范与团队习惯。

JavaScript中实现单例模式的核心是:确保一个类只有一个实例,并提供全局访问点。由于JS没有类的私有成员和构造器控制机制,实现方式更灵活但也需注意闭包、模块作用域和ES6+语法特性。
利用立即执行函数返回一个对象,内部变量被闭包保护,外部无法重复创建实例。
const Singleton = (function() {
let instance = null;
function createInstance() {
return { data: 'I am the only instance' };
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
// 使用
const a = Singleton.getInstance();
const b = Singleton.getInstance();
console.log(a === b); // true
借助class语法和静态属性保存实例,构造函数限制多次初始化(可选throw错误)。
class Singleton {
constructor() {
if (Singleton.instance) {
throw new Error('Use Singleton.getInstance() instead');
}
this.data = 'Singleton instance';
Singleton.instance = this;
}
static getInstance() {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
ES6模块本身具有“单例”语义:一个模块文件无论被import多少次,都只执行一次,导出对象始终是同一个引用。
新快购物系统是集合目前网络所有购物系统为参考而开发,不管从速度还是安全我们都努力做到最好,此版虽为免费版但是功能齐全,无任何错误,特点有:专业的、全面的电子商务解决方案,使您可以轻松实现网上销售;自助式开放性的数据平台,为您提供充满个性化的设计空间;功能全面、操作简单的远程管理系统,让您在家中也可实现正常销售管理;严谨实用的全新商品数据库,便于查询搜索您的商品。
0
立即学习“Java免费学习笔记(深入)”;
// singleton.js
export const instance = {
data: 'Module-based singleton',
count: 0,
increment() { this.count++; }
};
// app.js
import { instance as a } from './singleton.js';
import { instance as b } from './singleton.js';
console.log(a === b); // true
当单例需要首次创建时传入配置,又不希望每次调用都重新初始化,可用惰性工厂函数封装。
const ConfigurableSingleton = (function() {
let instance = null;
let config = null;
return {
getInstance: function(options = {}) {
if (!instance) {
config = { ...options, createdAt: Date.now() };
instance = { config, doSomething() { return 'done'; } };
}
return instance;
}
};
})();
基本上就这些。模块模式最轻量可靠,闭包IIFE最通用,class写法最贴近传统OOP理解。选择哪种取决于项目规范、兼容要求和团队习惯——单例本身不复杂,但容易忽略初始化时机和测试隔离问题。
以上就是JavaScript中如何实现单例模式_常见实现方式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号