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

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

问题描述

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

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


  1. 我何时在Angular中使用static应用程序级别提供的服务?那是胡说八道吗?

  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服务中有意义。在某些情况下,我们实际上并不需要使用服务的实例,并且我们不希望对它进行新的依赖,我们只需要访问我们的服务所携带的方法。这里有 static 成员。

They do, of course, make sense in Angular services. There are situations where we don't actually need to use an instance of the service, and we don't want to make a new dependency on it, we only need the 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
    }
}

2)静态方法对性能没有影响。正如我们上面已经确定的那样,它们不依赖于类的任何实例,并且调用这些方法绝不会实例化类。

2) Static methods have no impact 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天全站免登陆