JavaScript 中的单例模式 (singleton in Javascript)
单例模式的基本结构:
1 2 3 | MyNamespace.Singleton = function () { return {}; }(); |
比如:
1 2 3 4 5 6 7 8 9 10 11 12 | MyNamespace.Singleton = ( function () { return { // Public members. publicAttribute1: true , publicAttribute2: 10, publicMethod1: function () { ... }, publicMethod2: function (args) { ... } }; })(); |
但是,上面的Singleton在代码一加载的时候就已经建立了,怎么延迟加载呢?想象C#里怎么实现单例的:)采用下面这种模式:
1 2 3 4 5 6 7 8 9 10 | MyNamespace.Singleton = ( function () { function constructor() { // All of the normal singleton code goes here. ... } return { getInstance: function () { // Control code goes here. } } })(); |
具体来说,把创建单例的代码放到constructor里,在首次调用的时候再实例化:
完整的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | MyNamespace.Singleton = ( function () { var uniqueInstance; // Private attribute that holds the single instance. function constructor() { // All of the normal singleton code goes here. ... } return { getInstance: function () { if (!uniqueInstance) { // Instantiate only if the instance doesn't exist. uniqueInstance = constructor(); } return uniqueInstance; } } })(); |
关注作者
作者: JadePeng
出处:https://www.cnblogs.com/xiaoqi/archive/2010/06/09/1755056.html
版权:本文采用「署名-非商业性使用-相同方式共享 4.0 国际(欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接) 」知识共享许可协议进行许可。
标签:
JavaScript
, singleton
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了