js-单例模式

  当我们需要利用 js 创建一个类的唯一对象时,应该如何实现呢?

  这时单例模式的价值就体现出来了,在学习单例模式之间 先看看这个代码

            function Cat () {
       	    }
       	    Cat.prototype.run = function () {
       	    	console.log('run run');
       	    }
       	    var cat = new Cat();       	    
       	    cat.run(); 

运行结果当然是: 
 run run

那运行这个代码呢?

            function Cat () {
       	    	return this;
       	    }
       	    Cat.prototype.run = function () {
       	    	console.log('run run');
       	    }
       	    var cat = new Cat();       	    
       	    cat.run();

结果也是: 
 run run
 你会发现 Cat 函数内不管是否含有 return this;  用 new关键字生成的 cat  都能调用 run方法。

也就是说这个函数内部默认是有  return this; 这个代码的 ,在 函数外部 this赋值给 cat ,这时cai就可以调用 run 方法了。

明白这一点实现单例模式就变得简单了,只要我们在生成对象时 返回的都是同一个 this 就可以实现单例

 首先想到的是利用全局变量保存这个this 像这样

             function Cat () {
       	    	if(typeof single_instance == 'undefined'){
       	    		single_instance = this;
       	    	}
       	    	return single_instance;
       	    }
       	    Cat.prototype.run = function () {
       	    	console.log('run run');
       	    }
       	    var cat1 = new Cat();       	    
       	  	var cat2 = new Cat();  
       	  	console.log(cat1 === cat2);
打印结果是: true

这时我们就实现了单例模式

但是这里存在一个问题,利用全局变量保存this, 它就可能被覆盖掉,也有覆盖掉别的对象的可能。

那就不能用全局变量保存this,我们可以将这个this利用构造本身属性进行保存

这是实现代码

function Cat () {
       	    	if( !Cat.single_instance ){
       	    		Cat.single_instance = this;
       	    	}
       	    	return Cat.single_instance;
       	    }
       	    Cat.prototype.run = function () {
       	    	console.log('run run');
       	    }
       	    var cat1 = new Cat();    	    
       	  	var cat2 = new Cat();
       	  	console.log(cat1 === cat2);

利用这种方法实现单例模式 Cat的属性是公开的 也存在被修改的风险

只是比利用全局变量哪种方法好点
实现单利模式 推荐最后一种方法
 




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值