JavaScript单例模式

一、什么是单例

  意思是指获取的对象只有一份。

二、最通用的单例 

任何时刻获取SingLeton.instance都是同一个对象

1  var SingLeton={
2        instance:{
3             property:1,
4             getProperty:function(){return this.property;}
5         }  
6 }

三、转变成通过函数的方法来获取对象

类似于SingLeton()(),但是问题来了,每次执行都会重新创建instance对象,如果已经存在那么无需再创建

var Singleton=function(){
    var instance={
        property:1,
        getProperty:function(){return this.property;}
    };

    var getInstance=function(){
        return instance;
    }
    return getInstance;

}
console.log(Singleton()());
var Singleton=function(){
    var instance=null;
function createInstance(){ return { property:1, getProperty:function(){return this.property;} }; } var getInstance=function(){ instance=instance||createInstance(); return instance; } return getInstance; } console.log(Singleton()());

问题又来了,怎么不像其他语言那样,通过SingLeton.getInstance()来获取对象呢

四、自调用函数

要想改造成SingLeton.getInstance(),那SingLeton必须一出来就是一个对象,该对象包含一个方法,可以返回instance对象,我们想到采用让函数立即执行的方式

 
 
var Singleton=(function(){
    var instance=null;
    function createInstance(){
console.log("create");
return { property:1, getProperty:function(){return this.property;} }; } return { getInstance:function(){ instance=instance||createInstance(); return instance; } } })() console.log(Singleton.getInstance());
console.log(Singleton.getInstance());

//result:
create 
Object {property: 1}getProperty: (){return this.property;}
 
  
Object {property: 1}getProperty: (){return this.property;}
 
 
 

至此单例出来了,可以验证下

 

 

转载于:https://www.cnblogs.com/webWf/p/itwf.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值