前端(JavaScript)中单例模式的实现与应用实例_javascript技巧
前端单例模式与后端实现的核心思想相同,但由于JavaScript的运行环境和语言特性,实现方式有所不同:
const singleton = { property1: "value1", property2: "value2", method1() { // 方法实现 }, method2() { // 方法实现 }};// 使用singleton.method1();
特点:
class Singleton { constructor() { if (Singleton.instance) { return Singleton.instance; } this.property = 'value'; Singleton.instance = this; // "私有"成员约定(实际仍可访问) this._privateProperty = 'private'; } // 静态方法获取实例 static getInstance() { if (!Singleton.instance) { Singleton.instance = new Singleton(); } return Singleton.instance; } publicMethod() { console.log('Public method'); } // "私有"方法约定 _privateMethod() { console.log('Private method'); }}// 使用const instance1 = new Singleton(); // 或者 Singleton.getInstance()const instance2 = new Singleton();console.log(instance1 === instance2); // true
注意:ES6 class中的"私有"成员(以下划线开头)只是约定,实际上仍可访问。ES2022正式引入了私有字段语法:
// Redux的store是典型的单例import { createStore } from 'redux';const store = createStore(reducer);
全局配置管理
// cache.jsconst cache = { data: {}, get(key) { return this.data[key]; }, set(key, value) { this.data[key] = value; }, clear() { this.data = {}; }};export default cache;
模态框/对话框管理
class Singleton { private static instance: Singleton; private privateProperty: string = 'private'; private constructor() {} // 私有构造函数 public static getInstance(): Singleton { if (!Singleton.instance) { Singleton.instance = new Singleton(); } return Singleton.instance; } public publicMethod(): void { console.log('Public method'); } private privateMethod(): void { console.log('Private method'); }}// 使用const instance1 = Singleton.getInstance();const instance2 = Singleton.getInstance();console.log(instance1 === instance2); // true
// 创建Context本身就是单例const AppContext = React.createContext();// 提供值
Vue中的provide/inject:
// 提供export default { provide() { return { sharedService: this.sharedService }; }, data() { return { sharedService: new SharedService() }; }};// 注入export default { inject: ['sharedService']};
Angular中的服务:
@Injectable({ providedIn: 'root' // 应用级单例})export class DataService { // 服务实现}
单例模式在前端领域的发展呈现出两个明显趋势:
框架集成化:现代前端框架已经将单例模式的思想内化为状态管理方案(如Redux Store、Vue Pinia Store)
微前端适配:在微前端架构中,单例模式需要特殊设计以实现跨应用共享:
// 主应用导出window.sharedServices = window.sharedServices || { auth: new AuthService(), analytics: new AnalyticsService()};
在实际开发中,应当根据以下因素选择实现方式:
到此这篇关于前端(JavaScript)中单例模式的实现与应用的文章就介绍到这了,更多相关JS中单例模式实现内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
本文地址: https://www.earthnavs.com/jishuwz/9a52269733eb496607b1.html



















