JavaScript中单例模式的实现

单例模式

单例模式的定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
单例模式是一种常用的模式,有一些对象我们只需要一个,比如线程池、全局缓存、浏览器中的windows对象等。在JavaScript开发中,单例模式的用途同样非常广泛。比如当我们单击登录按钮时,页面中会出现一个登录浮窗,而这个登录浮窗是唯一的,无论单击多少次登录按钮,这个浮窗只会被创建一次,那么这个登录浮窗就适合用单例模式来创建。

单例模式实现

  function Test(name){
      if(typeof Test.intance === 'object'){
        return Test.intance;
      }
      this.name = name;
      Test.intance = this;
    }
    const a = new Test('one'); 
    // Test.intance = {};   问题:外部可更改此变量
    const b = new Test(); 
    console.log(a === b);   // true
function Test(name){
      let instance = this;
      this.name = name;
      Test = function(){
        return instance;
      }
    }
    const a = new Test();
    // Test.prototype.lastName='h'; 问题:两个对象并不是同一个构造函数创建
    const b = new Test();
    console.log(a === b,b.lastName);    // true undefined
const Test = (function(){
      let instance;
      return function(name){
        if(typeof instance === 'object'){
          return instance;
        }
        this.name = name;
        instance = this;
      }
    })()
    const a = new Test();
    Test.prototype.lastName = 'h';
    const b = new Test();
    console.log(a === b,b.lastName); // true h
单例模式高级使用,让普通函数变成单例模式
const getSingle = function(func){
      let result;
      return function(){
        if(!result){
          result = func.apply(this,arguments);
        }
        return result;
      }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值