【问题标题】:Singleton Access Private methods acces public methods单例访问私有方法访问公共方法
【发布时间】:2013-11-25 11:55:21
【问题描述】:

我创建了一个类,但在从私有方法访问公共方法时遇到了一点麻烦。我的例子是这样的:

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();

似乎范围完全不同。我应该以不同的方式创建单例吗?

【问题讨论】:

  • 私有“方法”在哪里调用?
  • @Bergi 抱歉,刚刚添加。在 init() 中调用;
  • @DevinDixon 你能提供你想如何使用它的示例吗?
  • @Grundy 我认为上面的示例非常精简以满足任何人的需要。我使用的案例是在页面上进行动作跟踪。我希望与服务器的所有通信都是私有的,但获取页面高度、浏览器类型等方法是公开的。

标签: javascript design-patterns singleton


【解决方案1】:

那么为什么你不想使用这样的东西:

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

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

如果您的问题正式提出,您需要像这样更改您的代码

...
function init() {

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

    privateMethod();

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

        publicMethod: publicMethod

    };

};
...

【讨论】:

  • 那不是单身。我只想要一次实例
  • mySingleton 是一个变量
  • 您发布的示例将被称为显示模块,与单例不同。
  • 你的实现有什么不同?
【解决方案2】:

不要使用那个额外的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();

【讨论】:

    猜你喜欢
    • 2015-09-13
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多