简体   繁体   中英

Singleton Access Private methods acces public methods

I have created a single class but I'm having a little trouble accesing the public methods from the private ones. My example is this:

var mySingleton = (function () {

  function init() {

    function privateMethod(){
        publicMethod();
        //this.publicMethod() also doesn't work
    }

    privateMethod();

    return {

      publicMethod: function () {
        console.log( "The private method called me!" );
      }
    };
  };

  return {
    getInstance: function () {

      if ( !instance ) {
        instance = init();
      }

      return instance;
    }
  };
})();

var singleton = mySingleton.getInstance();

It seems that the scopes are completely different. Should I be creating a singleton in a different way?

So why you don't want use something like this:

var mySingleton = (function () {
    /*private methods*/

    return {
      /*public methods*/
    }
})();

if approached formally by your question you need to change your code like this

...
function init() {

    function privateMethod(){
        publicMethod();//OK
    }

    privateMethod();

    function publicMethod(){
        console.log( "The private method called me!" );
    }
    return {

        publicMethod: publicMethod

    };

};
...

Don't use that additional init function. And you will have to access the public methods on the instance , ie the object which you had returned from init .

var mySingleton = (function () {
  var instance = null;
  function privateMethod(){
    instance.publicMethod();
  }

  return {
    getInstance: function () {
      if ( !instance ) {
        instance = {
          publicMethod: function () {
            console.log( "The private method called me!" );
          }
        };
        privateMethod();
      }
      return instance;
    }
  };
})();

var singleton = mySingleton.getInstance();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM