色尼玛亚洲综合影院,亚洲3atv精品一区二区三区,麻豆freexxxx性91精品,欧美在线91

JavaScript 設(shè)計模式學習 Singleton

復(fù)制代碼 代碼如下:
/* Basic Singleton. */
var Singleton = {
attribute1: true,
attribute2: 10,
method1: function() {
},
method2: function(arg) {
}
};
單件模式最主要的用途之一就是命名空間:
/* GiantCorp namespace. */
var GiantCorp = {};
GiantCorp.Common = {
// A singleton with common methods used by all objects and modules.
};
GiantCorp.ErrorCodes = {
// An object literal used to store data.
};
GiantCorp.PageHandler = {
// A singleton with page specific methods and attributes.
};
利用閉包在單件模式中實現(xiàn)私有方法和私有變量:
GiantCorp.DataParser = (function() {
// Private attributes.
var whitespaceRegex = //s+/;
// Private methods.
function stripWhitespace(str) {
return str.replace(whitespaceRegex, '');
}
function stringSplit(str, delimiter) {
return str.split(delimiter);
}
// Everything returned in the object literal is public, but can access the
// members in the closure created above.
return {
// Public method.
stringToArray: function(str, delimiter, stripWS) {
if(stripWS) {
str = stripWhitespace(str);
}
var outputArray = stringSplit(str, delimiter);
return outputArray;
}
};
})(); // Invoke the function and assign the returned object literal to
// GiantCorp.DataParser.
實現(xiàn)Lazy Instantiation 單件模式:
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;
}
}
})();
MyNamespace.Singleton.getInstance().publicMethod1();

JavaScript技術(shù)JavaScript 設(shè)計模式學習 Singleton,轉(zhuǎn)載需保留來源!

鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。

主站蜘蛛池模板: 湘潭县| 沐川县| 蕉岭县| 霍州市| 驻马店市| 额敏县| 衡南县| 普兰县| 大荔县| 昌江| 青岛市| 锡林郭勒盟| 灵台县| 清远市| 新巴尔虎右旗| 正定县| 车致| 陆河县| 梁平县| 麦盖提县| 云和县| 南昌县| 大安市| 保德县| 策勒县| 会泽县| 云浮市| 三江| 高清| 黄石市| 古交市| 色达县| 灵丘县| 京山县| 卢湾区| 东明县| 师宗县| 鹤峰县| 渝中区| 旺苍县| 花垣县|