简体   繁体   English

单例访问私有方法访问公共方法

[英]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. 不要使用该附加的init函数。 And you will have to access the public methods on the instance , ie the object which you had returned from init . 并且您将必须访问instance上的公共方法,即您从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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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