JavaScript 中的单例模式 (singleton in Javascript)

本文详细解析了JavaScript单例模式的基本结构,并深入探讨了如何通过延迟加载方式改进单例模式的实例化过程,以提升代码的灵活性和模块化能力。通过将创建单例的代码移至构造函数内部并引入私有属性,实现了在首次调用时才实例化的功能,有效避免了代码一加载就建立实例可能带来的性能开销。

单例模式的基本结构:

MyNamespace.Singleton = function() {
return {};
}();

比如:

MyNamespace.Singleton = (function() {
return { // Public members.
publicAttribute1: true,
publicAttribute2: 10,
publicMethod1: function() {
...
},
publicMethod2: function(args) {
...
}
};
})();

 

但是,上面的Singleton在代码一加载的时候就已经建立了,怎么延迟加载呢?想象C#里怎么实现单例的:)采用下面这种模式:

MyNamespace.Singleton = (function() {
function constructor() { // All of the normal singleton code goes here.
...
}
return {
getInstance: function() {
// Control code goes here.
}
}
})();

具体来说,把创建单例的代码放到constructor里,在首次调用的时候再实例化:

完整的代码如下:

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;
}
}
})();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值