JavaScript中单例模式的实现

下面记录两种单例模式的实现方式:

第一种,也是比较常见的一种

 1 var Single = function(){
 2     if(typeof Single.instance === "object"){
 3         return Single.instance;    
 4     }
 5     Single.instance = this;
 6 };
 7 
 8 var i1 = new Single();
 9 var i2 = new Single();
10 alert(i1 === i2);//true
alert(typeof(Single.instance));//object

这种方法的缺点是instance是公开的。

第二种,是用闭包的方法,这里用的了函数的自身重写

 1 var Single = function(){
 2     var instance = this;
 3     //一些其他的属性。。。
 4     //自身重写
 5     Single = function(){
 6         return instance;        
 7     };
 8 };
 9 
10 var i1 = new Single();
11 var i2 = new Single();
12 alert(i1 === i2);
  alert(typeof(Single.instance));//undefined

这样instance就不可见了。(完)^_^

参考资料:http://www.slideshare.net/stoyan/javascript-patterns

posted @ 2012-09-16 12:09  yuezk  阅读(527)  评论(0编辑  收藏  举报