javascript 单例 public 方法 "not a function"

javascript singleton public method "not a function"

我放弃了。我通常是一名 C# 开发人员,但对于这个特定项目我需要 javascript。

我有一个列表,我想用一些 setter 和 getter(以及 public 方法与私有辅助方法)进行保护。为此,我按照 post 中描述的 Addy Osmani 的单例模式实现了单例模式:http://robdodson.me/javascript-design-patterns-singleton/

但是,当我尝试访问 public 方法时,出现错误 "publicMethod is not a function"。

我有一个连接到 "addToList" 的按钮,我只想打印出消息作为开始。

为什么它看不到我的方法?

angular
.module('bacnetui')
.controller('bacnetuiController', function($scope, devicesFactory,){

   devicesFactory.getDevices().then(function (response){
     $scope.devices = response.data;
   }, function(error) {
    console.log(error);
   });


   $scope.mySingleton = (function () {
    // Instance stores a reference to the Singleton
    var instance;

    function init() {
      // Singleton
      var list = [];

      // Private methods and variables
      function indexOfDevice(dev){
       ...
     }

     function hasBacnet(dev,obj,prop){
       ....
     }
     function newBacnet(obj,prop){
        ....
     }

      return {

        // Public methods and variables
        publicMethod: function () {
          console.log( "The public can see me!" );
        },

        publicProperty: "I am also public"
      };
    };

    return {
      // Get the Singleton instance if one exists
      // or create one if it doesn't
      getInstance: function () {
        if ( !instance ) {
          instance = init();
        }
        return instance;
      }
    };
  })();


  $scope.addToList = function(device,obj,prop) {
    console.log("found a function: " + $scope.mySingleton.publicMethod());

    //$scope.myList.addBacnet(device,obj,prop);
  };

  $scope.removeFromList = function(device,obj,prop) {};

  $scope.saveToFile = function(){

  };
});

正如@Robby 在评论中指出的那样,您需要使用 $scope.mySingleton.getInstance().publicMethod()

流程如下:

  $scope.mySingleton = (function () {
    ...
    function init() {
      ...
      return {
        publicMethod: function () {
          ...
        },
      };
    };

    return {
      // Get the Singleton instance if one exists
      // or create one if it doesn't
      getInstance: function () {
        if ( !instance ) {
          instance = init();
        }
        return instance;
      }
    };
  })();

上面的结构 returns mySingleton 分配给它的对象为:

{
   getInstance: function() {...}
}

一旦你调用它,你就可以访问 init() 返回的目标 publicMethod()