最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript的單例模式 (singleton in Javascript)

 更新時(shí)間:2010年06月11日 00:28:44   作者:  
JavaScript的單例模式 (singleton in Javascript)
單例模式的基本結(jié)構(gòu):
復(fù)制代碼 代碼如下:

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

比如:
復(fù)制代碼 代碼如下:

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

但是,上面的Singleton在代碼一加載的時(shí)候就已經(jīng)建立了,怎么延遲加載呢?想象C#里怎么實(shí)現(xiàn)單例的:)采用下面這種模式:
復(fù)制代碼 代碼如下:

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

具體來(lái)說(shuō),把創(chuàng)建單例的代碼放到constructor里,在首次調(diào)用的時(shí)候再實(shí)例化:
完整的代碼如下:
復(fù)制代碼 代碼如下:

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;
}
}
})();

相關(guān)文章

最新評(píng)論

镇平县| 沈阳市| 商都县| 盐源县| 乃东县| 鹤庆县| 马鞍山市| 乡城县| 满洲里市| 图片| 松阳县| 克拉玛依市| 大港区| 永年县| 土默特右旗| 邢台市| 开封县| 吕梁市| 儋州市| 阳原县| 建昌县| 靖江市| 霍邱县| 敦化市| 资溪县| 衡南县| 金沙县| 嘉鱼县| 德庆县| 祁连县| 银川市| 秀山| 格尔木市| 彰化市| 无为县| 剑川县| 建德市| 石屏县| 乌审旗| 广丰县| 临武县|