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

JavaScript 設(shè)計(jì)模式學(xué)習(xí) Singleton

 更新時(shí)間:2009年07月27日 17:41:07   作者:  
JavaScript設(shè)計(jì)模式學(xué)習(xí) 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.
};
利用閉包在單件模式中實(shí)現(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.
實(shí)現(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();

相關(guān)文章

  • Javascript 類與靜態(tài)類的實(shí)現(xiàn)

    Javascript 類與靜態(tài)類的實(shí)現(xiàn)

    在Javascript里,對(duì)面向?qū)ο蟛](méi)有一個(gè)直接的實(shí)現(xiàn),對(duì)于代碼方面也是非常的靈活。
    2010-04-04
  • 最新評(píng)論

    平邑县| 庆阳市| 诸城市| 普陀区| 石阡县| 满城县| 乐平市| 临夏县| 丽水市| 津南区| 缙云县| 嘉善县| 繁昌县| 黄梅县| 广南县| 克什克腾旗| 临西县| 吕梁市| 绥江县| 田林县| 株洲市| 嘉荫县| 永善县| 岳阳县| 保康县| 芜湖县| 鄂温| 阿拉善右旗| 怀集县| 隆安县| 安吉县| 布尔津县| 昭苏县| 安化县| 涿州市| 江津市| 朝阳县| 佛山市| 临泉县| 乡城县| 呼和浩特市|