AngularJS 函数即 returns 一个命名函数

AngularJS function that returns a named function

以下是我在 Angular 中尝试了解有关服务的更多信息时获得的一些示例代码。我感到困惑的不是服务方面,而是构成服务的功能。函数 returns startMonitoring: function(){...}。我以前从未见过这个,我想知道它是如何使用的。 startMonitoring 是函数名吗?包含函数return时函数是否执行?这种return有名字吗?

batchModule.factory('routeTemplateMonitor', ['$route', 'batchLog', '$rootScope',
  function($route, batchLog, $rootScope) {
    return {
      startMonitoring: function() {
        $rootScope.$on('$routeChangeSuccess', function() {
          batchLog($route.current ? $route.current.template : null);
        });
      }
    };
  }]);

https://docs.angularjs.org/guide/services 中讨论服务的示例代码。

您的工厂创建了一个对象,其函数名称为 startMonitoring 并在您调用该函数时执行。

所以要使用它:

monitor.startMonitoring();

在本页 Working with object 使用 Object.create 方法 部分,您将看到解释。​​

希望对您有所帮助!

编辑:return 类型只是一个普通的 javascript 对象

这是一个 anonymous function expression attached as value to a property of an object literal

可以写成:

batchModule.factory('routeTemplateMonitor', ['$route', 'batchLog', '$rootScope',
   function($route, batchLog, $rootScope) {
       function startMonitoring() {
           $rootScope.$on('$routeChangeSuccess', function() {
              batchLog($route.current ? $route.current.template : null);
           });
       }
       var service = { startMonitoring: startMonitoring };
       return service;
   };
]);

该函数只能在 运行 块中调用一次:

app.run(['routeTemplateMonitor', function(routeTemplateMonitor) {
     routeTemplateMonitor.startMonitoring();
}]);

从控制器调用它存在多次调用导致内存泄漏的风险,因为控制器是由 ng-viewng-ifng-repeat 等指令创建和销毁的。


自动启动监视器

或者在实例化工厂时可以自动启动监视器:

batchModule.factory('routeTemplateMonitor', ['$route', 'batchLog', '$rootScope',
   function($route, batchLog, $rootScope) {
       function startMonitoring() {
           $rootScope.$on('$routeChangeSuccess', function() {
              batchLog($route.current ? $route.current.template : null);
           });
       }
       var service = { anotherMethod: method };
       startMonitoring();
       return service;
   };
]);
app.run(['routeTemplateMonitor', function(routeTemplateMonitor) {
     console.log("Route Template Monitor Started");
}]);