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

首頁 > 開發 > JS > 正文

JavaScript的單例模式 (singleton in Javascript)

2024-09-06 12:45:49
字體:
來源:轉載
供稿:網友
單例模式的基本結構:
代碼如下:
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;
}
}
})();
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 同心县| 德江县| 惠来县| 株洲市| 宜丰县| 定南县| 邻水| 金门县| 海南省| 长阳| 南昌县| 株洲市| 永新县| 山东省| 赞皇县| 太仓市| 绍兴县| 徐汇区| 元朗区| 阿瓦提县| 和静县| 祁门县| 沿河| 巴林右旗| 洛南县| 泗水县| 宁安市| 德钦县| 石屏县| 阿克苏市| 磴口县| 赣榆县| 茶陵县| 池州市| 凌海市| 那曲县| 且末县| 固原市| 酒泉市| 阿拉善盟| 金堂县|