js singleton

方案一:利用闭包的两个作用,可以变通地读到内部的变量。

方案二: 是可以让这些变量始终在内存中。


方案一 
 1   var SingletonTester = (function () { 
 2         //单例方法 
 3         function Singleton(args) { 
 4             var args = args || {}; 
 5             this.name = 'SingletonTester'; //方法对外的属性,另外一种方式就是返回对象 
 6             this.pointX = args.pointX || 6; 
 7             this.pointY = args.pointY || 10; 
 8         } 
 9 
10         //单例实例 
11         var instance; 
12 
13         //返回对象 
14         return { 
15             name: 'SingletonTester', 
16 
17             getInstance: function (args) { 
18                 if (instance === undefined) { 
19                     instance = new Singleton(args); 
20                 } 
21                 return instance; 
22             } 
23         }; 
24     })(); //直接执行该方法 
25 
26     //测试 
27     var test = SingletonTester.getInstance({ pointX: 5 }); 
28     console.log(test.pointX);
29  
30 
31  
32 
33  
方案二 
 
 1  function Universe() { 
 2       // 判断是否存在实例 
 3       if (typeof Universe.instance === 'object') { 
 4           return Universe.instance; 
 5       } 
 6 
 7       // 其它内容 
 8       this.start_time = 0; 
 9       this.bang = "Big"; 
10 
11       // 缓存 
12       Universe.instance = this; 
13 
14       // 隐式返回this 
15   } 
16 
17   // 测试 
18   var uni = new Universe(); 
19   var uni2 = new Universe(); 
20   console.log(uni === uni2); // true
21  
原文地址:https://www.cnblogs.com/zoucaitou/p/4172017.html