javascript设想形式--单例形式

javascript单例形式总结

1.什么是单例形式?

单例形式的定义是:一个类唯一一个实例,而且能够在全局接见
在一样平常开辟中,单例形式的运用非常普遍。比方开辟登录浮窗,我们不管点击登录按钮多少次,浮窗都只会建立一次。
这时候,浮窗就很合适运用单例形式来建立。

2.完成单例形式

var CreatePopbox = function(html){
    this.html = html;
    this._init();
};

CreatePopbox.prototype._init = function(){
    this.div = document.createElement('div');
    this.div.innerHTML = this.html;
    this.div.style.display = 'none';
    document.body.appendChild(this.div);

};

CreatePopbox.prototype.show = function(){
    this.div.style.display = 'block';
};

CreatePopbox.prototype.hide = function(){
    this.div.style.display = 'none';
};

//经由过程代办函数到达单例形式的结果

var proxysingleCreatePopbox = (function(){
    var instance;
    return function(html){
        if(!instance){
            instance = new CreatePopbox(html);
        }
        return instance;
    }
})();


//建立CreatePopbox:

var a = new proxysingleCreatePopbox("this is a");
var b = new proxysingleCreatePopbox("this is b");

console.log(a === b);  //true

能够看到,a和b都指向了同一个实例,实行new proxysingleCreatePopbox("this is b") 时,并不会从新天生一个新的CreatePopbox
这相符了单例形式的中心:确保实例只要一个

经由过程以上例子,我们已相识单例形式的完成体式格局,但另有一些缺点:

建立对象和单例治理的逻辑都合在proxysingleCreatePopbox里边,当须要建立其他单例时,只能把proxysingleCreatePopbox拷贝一次。

因而,我们须要把代码再革新一下,把稳定的部份断绝出来。

//
var getSingle = function(fn){
  var singleObj;
  return function(obj){
    if(!singleObj){
      singleObj = new fn(obj);
    }
    return singleObj;
  }
}



var CreatePopbox = function(opation){
  this.html = opation.html;
  this._init();
};

CreatePopbox.prototype._init = function(){
  this.div = document.createElement('div');
  this.div.innerHTML = this.html;
  document.body.appendChild(this.div);
};

var singlePopbox = getSingle(CreatePopbox);

var a = new singlePopbox({html:"this is a"});

//建立一个新的单例

var CreateTipbox = function(opation){
  this.div = document.createElement('div');
  this.div.style.color = opation.color;
  this.div.innerHTML = opation.html;
  document.body.appendChild(this.div);
} 

//运用getSingle治理
var singleTipbox = getSingle(CreateTipbox);
var b = new singleTipbox({html:"this is b",color:"#f00"});

原文链接:javascript设想形式--单例形式

    原文作者:hczhi88
    原文地址: https://segmentfault.com/a/1190000010019122
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞