js单例使用
单例模式
1 var mySingleton = (function(){ 2 var instance; 3 function init(){ 4 function privateMehod(){ 5 console.log(111); 6 }; 7 var privateVar = '11111'; 8 var privateRandomNumber = Math.random(); 9 return { 10 publicMethod:function(){ 11 12 }, 13 publicVar:2222, 14 getRandomNumber:function(){ 15 return privateRandomNumber 16 } 17 } 18 }; 19 return { 20 getInstance: function(){ 21 if(! instance){ 22 instance = init(); 23 }; 24 return instance 25 } 26 } 27 })();
调用方式:
1. mySingleton // getInstance:function(){}
2. mySingleton.getInstance() // publicMethod: function, publicVar: 2222, getRandomNumber: function
3. mySingleton.getInstance().publicVar //222