JavaScript ES6 中的静态方法和 Angular 2 服务 [英] Static Methods and Angular 2 Services in JavaScript ES6

查看:22
本文介绍了JavaScript ES6 中的静态方法和 Angular 2 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

While coding an app with Angular 2 and multiple calculation services I faced the following questions:

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

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

This is a snap of the class, that provides me multiple calculation methods and is instantiated on application level:

@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 {
    ...
  }
}

感谢您的帮助.

推荐答案

  1. 静态类的方法,与实例方法不同,属于(可见)类本身(不是它的实例).它们不依赖于类的实例成员,通常会从参数中获取输入,对其执行操作,并返回一些结果.他们独立行动.
  1. Static methods of a class, unlike instance methods, belong to (are visible on) the class itself (not an instance of it). They do not depend on the instance members of a class and will usually take input from the parameters, perform actions on it, and return some result. They act independently.

它们在 Angular 服务中确实有意义.在某些情况下,我们不能/实际上不需要使用服务的实例,并且我们不能/不想对其进行新的依赖,我们只需要访问我们的服务携带的方法.这里静态成员进来了.

They do make sense in Angular services. There are situations where we can't / don't actually need to use an instance of the service, and we can't / don't want to make a new dependency on it, we only need access to the methods our service carries. Here static members come in.

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

The example of using the static method defined in the service:

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. 静态方法对性能没有影响.正如我们在上面确定的那样,它们不依赖于类的任何实例,并且调用这些方法绝不会实例化类.
  1. Static methods have no impact on the performance. As we've ascertained above, they do not depend on any instance of the class, and invoking those methods will in no way instantiate the class.

有关详细信息,请参阅:http://www.typescriptlang.org/docs/handbook/classes.html

For more information, it's explained well on: http://www.typescriptlang.org/docs/handbook/classes.html

这篇关于JavaScript ES6 中的静态方法和 Angular 2 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆