• Blogs (9)
    • 📱 236 - 992 - 3846

      đź“§ jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • JavaScript: 3 ways to implement Singleton

    Blogs20132013-10-27


    JavaScript: 2+1 ways of Singleton implementation

    Here I list 2 ways of Singleton implementation, which refers to Stoyan Stefanov’s JavaScript Patterns.

    //1. rewrite constructor function in a closure:
    var Singleton = (function() {
      var instance;
      Singleton = function Singleton() {
        if(instance) {
          return instance;
        }
    
        instance = this;
    
        this.start_time = 0;
        this.others = "others";
      };
    }());
    
    // more directly:
    function Singleton() {
      var instance = this;
    
      this.start_time = 0;
      this.others = "others";
    
      Singleton = function() {
        return instance;
      };
    
    }
    
    //2. pretty cool: use static attribute of constructor:
    function Singleton() {
      if(typeof Singleton.instance === 'object') {
        return Singleton.instance;
      }
    
      this.start_time = 0;
      this.others = "others";
    
      Singleton.instance = this;
    }

    And, a parasitic constructor function mode:

    function Singleton() {
      var o;
      //rewrite constructor,
      //so next time directly return Singleton instance.
      Singleton = function Singleton() {
        return o;
      }
    
      // for dynamic prototype mode
      Singleton.prototype = this;
    
      // o.__proto__=Singleton
      o = new Singleton();
      //
      o.constructor = Singleton;
      this.start_time = 0;
      this.others = "others";
    
      return o;  //not return this!
    }