美文网首页
JS实现单例模式

JS实现单例模式

作者: 凯凯frank | 来源:发表于2020-03-14 19:36 被阅读0次

    单例模式比较简单,下面直接给出代码实现

    function Singleton(){
        this.instance = null;
    }
    //定义一个静态方法
    Singleton.getInstance = function(){
        if(!this.instance){
            this.instance = new Singleton()
        }
        return this.instance
    }
    
    var a = Singleton.getInstance()
    var b = Singleton.getInstance()
    
    console.log(a === b)
    

    知识点:js类方法

    在js中,函数是第一等公民,你可以把函数当成对象使用。当给函数添加一个方法时,比如上面的Singleton.getInstance=function(){},就相当于给函数添加了一个属性

    function Singleton(){
       this.instance = null;
       this.getInstance = function(){//可以访问私有变量
       }
    }
    

    相关文章

      网友评论

          本文标题:JS实现单例模式

          本文链接:https://www.haomeiwen.com/subject/jwqnshtx.html