javascript-單體模式
阿新 • • 發佈:2017-08-07
javascript 單體
<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>
javascript-單體模式