javascript singleton question

前端 未结 10 2042
闹比i
闹比i 2020-12-12 20:08

I just read a few threads on the discussion of singleton design in javascript. I\'m 100% new to the Design Pattern stuff but as I see since a Singleton by definition won\'t

10条回答
  •  -上瘾入骨i
    2020-12-12 20:31

    I stole this from CMS / CMS' answer, and changed it so it can be invoked as:

    MySingleton.getInstance().publicMethod1();
    

    With the slight alternation:

    var MySingleton = {                // These two lines
    
        getInstance: function() {      // These two lines
    
          var instance = (function() {
    
            var privateVar;
    
            function privateMethod () {
              // ...
              console.log( "b" );
            }
    
            return { // public interface
              publicMethod1: function () {
                  // private members can be accessed here
                  console.log( "a" );
               },
              publicMethod2: function () {
                // ...
                privateMethod();
              }
            };
          })();
    
          singleton = function () { // re-define the function for subsequent calls
            return instance;
          };
    
          return singleton(); // call the new function
        }
    }
    

提交回复
热议问题