您好,欢迎访问一九零五行业门户网

JavaScript的单例模式 (singleton in Javascript)_js面向对象

单例模式的基本结构:
复制代码 代码如下:
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;
}
}
})();
其它类似信息

推荐信息