国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

JavaScript的單例模式 (singleton in Javascript)

2019-11-21 00:26:13
字體:
供稿:網(wǎng)友
單例模式的基本結(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在代碼一加載的時候就已經(jīng)建立了,怎么延遲加載呢?想象C#里怎么實現(xiàn)單例的:)采用下面這種模式:
復(fù)制代碼 代碼如下:

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

具體來說,把創(chuàng)建單例的代碼放到constructor里,在首次調(diào)用的時候再實例化:
完整的代碼如下:
復(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;
}
}
})();
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 鞍山市| 澎湖县| 克什克腾旗| 浦县| 苍南县| 江门市| 民县| 翼城县| 衡阳县| 日土县| 九江县| 上犹县| 黄大仙区| 塔城市| 阿克| 大英县| 临安市| 正定县| 绥阳县| 济阳县| 澳门| 晴隆县| 宜宾县| 陈巴尔虎旗| 仁布县| 体育| 巨野县| 河北区| 安国市| 桐城市| 屏东县| 临湘市| 博野县| 卫辉市| 昔阳县| 聂荣县| 青河县| 墨竹工卡县| 汝阳县| 北碚区| 林周县|