<script type="text/javascript"> //简单单体模式 var singleton={ attr1:10, attr2:true, method1:function(){console.log(‘method1 ...‘)}, method2:function(){console.log(‘method2 ...‘)} } console.log(singleton.attr1) singleton.method1() //划分命名空间 var nameSpace1={} nameSpace1.singleton1={ attr1:10, attr2:true, method1:function(){console.log(‘method1 ...‘)}, method2:function(){console.log(‘method2 ...‘)} } nameSpace1.singleton2={ attr1:10, attr2:true, attr3:‘hello singleton‘, method1:function(){console.log(‘method1 ...‘)}, } //借用闭包创建单体,闭包主要用于保护数据 //命名空间 var nameSpace2={} nameSpace2.singleton=(function(){ //浏览器运行后,立即执行:私有成员变量 var name=‘cxiong‘ var age=29 var addr=‘beijing‘ var interest1=function(){console.log(‘coding ...‘)} var interest2=function(){console.log(‘play compute game ...‘)} //把块级作用域中的执行结果返回 return { name:name, age:age, addr:addr, int1:function(){interest1()}, int2:function(){interest2()} } })() nameSpace2.singleton.name=‘mm‘ console.log(nameSpace2.singleton.name) console.log(nameSpace2.singleton.age) nameSpace2.singleton.int1() </script>
时间: 2024-10-05 05:10:31