单例模式

解决代码开销,提高代码效率

var Model=function(id,html,open){
        this.id=id;
        this.html=html;
        this.open=false;
    }
    Model.prototype.create = function(){
        if(!this.open){       
            var model=document.createElement('div');
            model.innerHTML = this.html;
            model.id = this.id;
            document.body.appendChild(model);
            this.open = true;
            model.classList.remove('hide')          
            model.classList.add('show')   
        } 
    }
    Model.prototype.delete = function(){
        if(this.open){
            var model=document.getElementById('model');   
            document.body.removeChild(model);
            model.classList.add('hide') 
            this.open = false;
        }   
    }
    var createIntance = (function(){
        var instance;
        return function (){
            return instance || (instance = new Model('model','我是一个弹框')) //单例模式的核心,如果存在,则用存在的,不存在,则创建
        }
    })();
    var operate = {
        setModel:null,
        open:function(){
            this.setModel = createIntance();
            this.setModel.create();
        },
        delete:function(){
            this.setModel ? this.setModel.delete():'';
        }
    }
    document.getElementById("open").onclick=function(){
        operate.open();
    }
    document.getElementById("delete").onclick=function(){
        operate.delete();
    }

 

posted @ 2020-04-01 14:10  混名汪小星  阅读(155)  评论(0编辑  收藏  举报