zoukankan      html  css  js  c++  java
  • Javascript设计模式(一)

    1.单例模式

    javascript 单例模式定义命名空间

    // 定义命名空空间

        var Ming={
            g:function(id){
                return document.getElementById(id)
            },
            css:function(id,key,value){
                this.g(id).style[key]=value;
            }
        }
        console.log(Ming.g("box"));
        Ming.css("box","width","200px");
        Ming.css("box","height","200px");
        Ming.css("box","background","red");
    

      

    避免变量的冲突定义自己的命名空间。

    // 规范自己的代码库

        var G={
            Util:{
                util_method1:function(){},
                util_method2:function(){}
            },
            Tool:{
                tool_method1:function(){},
                tool_method2:function(){}
            },
            Ajax:{
                get:function(){},
                post:function(){}
            },
            Other:{
                other_method1:function(){},
                other_method2:function(){}
            }
    
        }
        //G.Ajax.get()
        //G.Tool.tool_method1();

    //定义无法修改的静态变量

     var Conf=(function(){
            var conf={
                MAX_NUM:100,
                MIN_NUM:1,
                COUNT:1000
            }
            return{
                get:function(name){
                    return conf[name]?conf[name]:null;
                }
            }
        })();
        var count=Conf.get('COUNT');
        console.log(count)
    

    //延迟创建单利模式(惰性创建)

    var LazySingle=(function(){
            var instance=null;
            function Single(){
                return {
                    publicMethod:function(){},
                    publicProperty:'1.0'
                }
            }
            return function(){
                if(!instance){
                    instance=Single();
                }
                return instance;
            }
        })();
    console.log(LazySingle().publicProperty);
  • 相关阅读:
    2020多校补题集
    2020牛客多校第10场C Decrement on the Tree树上路径删除
    主席树模板(查询区间第K大的元素)
    第一次小赛
    计算几何小知识整理
    咸鱼暂时退圈
    mysql 格式化时间
    mysql 中国省份城市数据库表
    CF786B Legacy (线段树优化建图模板)
    树上两点期望距离
  • 原文地址:https://www.cnblogs.com/dangou/p/7266675.html
Copyright © 2011-2022 走看看