JavaScript 单例模式
最近几天一直在看 js.
1 var SingletonTester = (function () { 2 3 //参数:传递给单例的一个参数集合 4 function Singleton(args) { 5 //设置args变量为接收的参数或者为空(如果没有提供的话) 7 var args = args || {}; 8 //设置name参数 9 this.name = 'SingletonTester'; 10 //设置pointX的值 11 this.pointX = args.pointX || 6; //从接收的参数里获取,或者设置为默认值 12 //设置pointY的值 www.2cto.com 13 this.pointY = args.pointY || 10; 14 } 15 16 //实例容器 17 var instance; 18 19 var _static = { 20 name : 'SingletonTester', 21 22 //获取实例的方法 23 //返回Singleton的实例 24 getInstance : function (args) { 25 if (instance === undefined) { 26 instance = new Singleton(args); 27 } 28 return instance; 29 } 30 }; 31 32 return _static; 33 34 })(); 35 36 var singletonTest = SingletonTester.getInstance({ 37 pointX : 5 38 }); 39 40 console.log(singletonTest.pointX); // 输出 5
sds