js实现单例模式
单例模式的概念
单例模式是一种设计模式,确保一个类只有一个实例,并提供全局访问点。在JavaScript中,可以通过多种方式实现单例模式。
使用对象字面量
最简单的单例模式实现方式是直接使用对象字面量。对象字面量在JavaScript中本身就是单例的。
const singleton = {
property: 'value',
method() {
console.log('Method called');
}
};
使用闭包和立即执行函数
通过闭包和立即执行函数(IIFE)可以创建一个私有作用域,确保实例的唯一性。
const Singleton = (function() {
let instance;
function createInstance() {
const object = new Object('I am the instance');
return object;
}
return {
getInstance() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
使用ES6类
在ES6中,可以通过类的静态方法和私有变量实现单例模式。
class Singleton {
static #instance;
constructor() {
if (Singleton.#instance) {
return Singleton.#instance;
}
Singleton.#instance = this;
}
static getInstance() {
if (!Singleton.#instance) {
Singleton.#instance = new Singleton();
}
return Singleton.#instance;
}
}
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // true
使用模块模式
JavaScript的模块系统天然支持单例模式,因为模块在首次导入时会被缓存,后续导入会返回相同的实例。

// singleton.js
let instance;
class Singleton {
constructor() {
if (instance) {
throw new Error('Use getInstance() instead');
}
instance = this;
}
static getInstance() {
if (!instance) {
instance = new Singleton();
}
return instance;
}
}
export default Singleton;
// app.js
import Singleton from './singleton.js';
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
注意事项
- 单例模式可能导致全局状态,增加代码的耦合性。
- 在多线程环境中需要额外处理,但JavaScript是单线程的,无需考虑此问题。
- 单例模式适合用于需要全局访问点且唯一实例的场景,如配置管理、日志记录等。






