JavaScript ES6 中的静态方法和 Angular 2 项服务

Static Methods and Angular 2 Services in JavaScript ES6

在使用 Angular 2 和多个计算服务编写应用程序时,我遇到了以下问题:

  1. 何时在应用程序级别提供的 Angular 服务中使用静态?那是胡说八道吗?
  2. 静态方法如何体现性能?假设有几个 hundret 对象同时调用同一个静态方法。这个方法是否实例化了不止一次?

这是class的一个快照,它为我提供了多种计算方法并在应用程序级别实例化:

@Injectable()
export class FairnessService {
  constructor(){}
  private static calculateProcentValue(value: number, from: number): number {
    return (Math.abs(value) / Math.abs(from)) * 100;
  }
  public static calculateAllocationWorth(allocation: Allocation): number {
    ...
  }
}

感谢您的帮助。

更新

我之前的回答是基于有限的理解。静态方法可用于 class 本身,而不是其中一个实例。

这里有一篇文章可以解释这个概念: https://javascript.info/static-properties-methods

seidme 的回答也很靠谱。

原创

静态方法在 Angular 应用程序中表示为全局变量(我认为?),因此我认为它们每个只会被实例化一次。因此,我认为它不会对性能产生很大影响(相对于每个需要它的组件的 class 的实例化。)

当我不想注入服务并获取实例只是为了利用 context-agnostic formatting/utility 方法时,我使用静态。 Application-wide 这些版本对我来说似乎不合理。

  1. class 的静态 方法,不同于实例 方法,属于(可见)class 本身(不是它的一个实例)。它们不依赖于 class 的实例成员,通常会从参数中获取输入,对其执行操作,并 return 一些结果。他们独立行动。

它们在 Angular 服务中确实有意义。有些情况我们不能/实际上不需要使用服务的实例,我们不能/不想对它产生新的依赖,我们只需要访问我们的服务携带的方法. static 位成员进来了。

服务中定义的静态方法使用示例:

import { FairnessService } from './fairness.service';

export class MyComponent {

    constructor() {
        // This is just an example of accessing the static members of a class.
        // Note we didn't inject the service, nor manually instantiate it like: let a = new A();
        let value = FairnessService.calculatePercentValue(5, 50);
        let value2 = FairnessService.calculatePercentValue(2, 80);

        console.log(value); // => 10
        console.log(value2); // => 2.5
    }
}
  1. 静态 方法对性能没有影响。正如我们在上面确定的那样,它们不依赖于 class 的任何实例,并且调用这些方法绝不会实例化 class.

有关更多信息,在以下位置有很好的解释:http://www.typescriptlang.org/docs/handbook/classes.html