整理历史知识-设计模式-单例模式

本文详细探讨了单例模式在JavaScript中的实现方式,包括通过函数和构造函数创建单例对象的方法,展示了如何确保对象的唯一性和全局访问性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 单个例子的模式 demo1

function singleCase (name){

this.name = name;

}

singleCase.prototype.sayHi = function(){

alert(this.name);

}

let getInstance = (function(){

var instance = null;

return function(name) {

if(!instance) { //相当于一个一次性阀门,只能实例化一次

instance = new singleCase(name);

}

return instance;

}

})();

let one = getInstance("one");

let two = getInstance("two");

 

// 单例模式 demo2

 

function Single (name){

this.name = name;

}

Single.prototype.say = function(){

alert(12);

}

Single.getInstance = function (...args){

if(this.instance){

return this.instance;

}

this.instance = new Single(...args)

return this.instance;

}

let a1 = Single.getInstance("a1")

let a2 = Single.getInstance("a2")

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值