Simplest/Cleanest way to implement singleton in JavaScript?

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

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

30条回答
  •  天命终不由人
    2020-11-22 05:45

    The clearest answer should be this one from the book Learning JavaScript Design Patterns by Addy Osmani.

    var mySingleton = (function () {
     
      // Instance stores a reference to the Singleton
      var instance;
     
      function init() {
     
        // Singleton
     
        // Private methods and variables
        function privateMethod(){
            console.log( "I am private" );
        }
     
        var privateVariable = "Im also private";
     
        var privateRandomNumber = Math.random();
     
        return {
     
          // Public methods and variables
          publicMethod: function () {
            console.log( "The public can see me!" );
          },
     
          publicProperty: "I am also public",
     
          getRandomNumber: function() {
            return privateRandomNumber;
          }
     
        };
     
      };
     
      return {
     
        // Get the Singleton instance if one exists
        // or create one if it doesn't
        getInstance: function () {
     
          if ( !instance ) {
            instance = init();
          }
     
          return instance;
        }
     
      };
     
    })();

提交回复
热议问题