Simplest/Cleanest way to implement singleton in JavaScript?

后端 未结 30 1085
名媛妹妹
名媛妹妹 2020-11-22 05:17

What is the simplest/cleanest way to implement singleton pattern in JavaScript?

30条回答
  •  心在旅途
    2020-11-22 05:46

    How about this way, just insure the class can not new again.

    By this, you can use the instanceof op, also, you can use the prototype chain to inherit the class,it's a regular class, but can not new it,if yuu want to get the instance just use getInstance

    function CA()
    {
        if(CA.instance)
        {
            throw new Error('can not new this class');
        }else{
            CA.instance = this;
        }
    
    }
    /**
     * @protected
     * @static
     * @type {CA}
     */
    CA.instance = null;
    /** @static */
    CA.getInstance = function()
    {
        return CA.instance;
    }
    
    CA.prototype = 
    /** @lends CA#*/
    {
        func: function(){console.log('the func');}
    }
    // initilize the instance
    new CA();
    
    // test here
    var c = CA.getInstance()
    c.func();
    console.assert(c instanceof CA)
    // this will failed
    var b = new CA();
    

    If you don't want to expose the instance member, just put it into a closure.

提交回复
热议问题