JavaScript_11设计模式(单体模式【五】)简单单体和闭包单体

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36282409/article/details/84260985
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>New Web Project</title>
    <script type="text/javascript" charset="UTF-8">
        //单体模式:(singleton)
        //1.简单单体模式:
     /*
        var Singleton={
            attr1:true,
            attr2:10,
            method1:function(){
                alert('我是方法一');
            },
            method2:function(){
                alert('我是方法二');
            }
                        
        };
        
      */  
      //  alert(Singleton.attr1);
        
        //单体的作用:2.划分命名空间(区分代码)Ext.Manager.attr1/method1
        /*
        //Ext.Array.some();
      //  MyCode
        var BHX={};
        
        BHX.Singleton={
              attr1:true,
            attr2:10,
            method1:function(){
                alert('我是方法一');
            },
            method2:function(){
                alert('我是方法二');
            }
        };
        BHX.Singleton.method1();
        */
        
        //2.借用闭包创建单体:闭包主要的目的,保护数据,不受外界所干扰。
        //命名空间
       var BHX={};
        BHX.Singleton=(function test(){
            //添加自己的私有成员。
            
            var a1=true;
            var a2=10;
           var f1=function(){
               
               alert('f1');
           };
            var f2=function(){
               
               alert('f2');
           };
            
            //把块级作用域的执行结果,直接赋给单体对象。
          return {
              
                attr1:a1,
                 attr2:a2,
            method1:function(){
               return f1();
            },
            method2:function(){
                 return f2();
            }
              
          };
                          
        })();
        
        alert(BHX.Singleton.attr1);
        BHX.Singleton.method1();
                      
    </script>
</head>
<body>
    <h1>New Web Project Page</h1>
</body>

猜你喜欢

转载自blog.csdn.net/weixin_36282409/article/details/84260985
今日推荐