JavaScript的单例模式 (singleton in Javascript)

时间:2010-06-11    点击:161   
单例模式的基本结构:
复制代码 代码如下:

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;
}
}
})();
EasySlider 基于jQuery功能强大简单易用的滑动门插件
cnblogs TagCloud基于jquery的实现代码
Js setInterval与setTimeout(定时执行与循环执行)的代码(可以传入参数)
js鼠标左右键 键盘值小结
JavaScript接口实现代码 (Interfaces In JavaScript)
> 返回     
地址:上海市普陀区胶州路941号长久商务中心 电话: QQ:
© Copyright 2012 上海网络 Product All Rights Reserved