js单例模式

1、使用构造函数的默认属性

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function A(name){
    // 如果已存在对应的实例
   if(typeof A.instance === 'object'){
       return A.instance
   }
   //否则正常创建实例
   this.name = name
    
   // 缓存
   A.instance =this
   return this
}
var a1 = new A()
var a2= new A()
console.log(a1 === a2)//true

 2、借助闭包

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var Head = (function () {
    var HeadClass = function () { }; // 声明HeadClass对象,无法在外部直接调用
    var instance; // 声明一个instance对象
    return function () {
        if (instance) { // 如果已存在 则返回instance
            return instance;
        }
        instance = new HeadClass() // 如果不存在 则new一个
        return instance;
    }
})();
var a = Head();
var b = new Head();
console.log(a===b) // true
var a = HeadClass(); // 报错,HeadClass is not defined

  

 3、立即执行函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var A;
(function(name){
    var instance;
    A = function(name){
        if(instance){
            return instance
        }
         
        //赋值给私有变量
        instance = this
         
        //自身属性
        this.name = name
    }
}());
A.prototype.pro1 = "from protptype1"
 
var a1 = new A('a1')
A.prototype.pro2 = "from protptype2"
var a2 = new A('a2')
 
console.log(a1.name)
console.log(a1.pro1)//from protptype1
console.log(a1.pro2)//from protptype2
console.log(a2.pro1)//from protptype1
console.log(a2.pro2)//from protptype2

 

posted @   dnoyeb  阅读(7242)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示