Simplest/Cleanest way to implement singleton in JavaScript?

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

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

30条回答
  •  春和景丽
    2020-11-22 05:26

    following is the snippet from my walk through to implement a singleton pattern. This occurred to me during an interview process and I felt that I should capture this somewhere.

    /*************************************************
       *     SINGLETON PATTERN IMPLEMENTATION          *
       *************************************************/
    
      //since there are no classes in javascript, every object is technically a singleton
      //if you don't inherit from it or copy from it.
      var single = {};
      //Singleton Implementations
      //Declaring as a Global Object...you are being judged!
    
    
      var Logger = function() {
        //global_log is/will be defined in GLOBAL scope here
        if(typeof global_log === 'undefined'){
          global_log = this;
        }
        return global_log;
      };
    
    
      //the below 'fix' solves the GLOABL variable problem but
      //the log_instance is publicly available and thus can be 
    
      //tampered with.
      function Logger() {
        if(typeof Logger.log_instance === 'undefined'){
          Logger.log_instance = this;
        }
    
    
        return Logger.log_instance;
       };
    
    
      //the correct way to do it to give it a closure!
    
    
      function logFactory() {
        var log_instance; //private instance
        var _initLog = function() { //private init method
          log_instance = 'initialized';
          console.log("logger initialized!")
        }
        return {
          getLog : function(){ //the 'privileged' method 
            if(typeof log_instance === 'undefined'){
              _initLog();
            }
            return log_instance;
          }
        };
      }
    
      /***** TEST CODE ************************************************
      //using the Logger singleton
      var logger = logFactory();//did i just gave LogFactory a closure?
      //create an instance of the logger
      var a = logger.getLog();
      //do some work
      //get another instance of the logger
      var b = logger.getLog();
    
    
      //check if the two logger instances are same?
      console.log(a === b); //true
      *******************************************************************/
    

    the same can be found on my gist page

提交回复
热议问题