Devin Dixon
Devin Dixon

Reputation: 12403

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?

Upvotes: 1

Views: 112

Answers (2)

Bergi
Bergi

Reputation: 664599

Don't use that additional init function. And you will have to access the public methods on the instance, i.e. 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();

Upvotes: 0

Grundy
Grundy

Reputation: 13381

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

    };

};
...

Upvotes: 1

Related Questions