[英]Static Methods and Angular 2 Services in JavaScript ES6
While coding an app with Angular 2 and multiple calculation services I faced the following questions:在使用 Angular 2 和多个计算服务编写应用程序时,我遇到了以下问题:
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 {
...
}
}
Thanks for helping.谢谢你的帮助。
They do make sense in Angular services.它们在 Angular 服务中确实有意义。 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
}
}
For more information, it's explained well on: http://www.typescriptlang.org/docs/handbook/classes.html有关更多信息,它的解释很好: http : //www.typescriptlang.org/docs/handbook/classes.html
Update更新
My answer before was based on a limited understanding.我之前的回答是基于有限的理解。 The static methods are available on a class itself, not on one of it's instantiations.静态方法可用于类本身,而不是其实例化之一。
Here's an article that can explain this concept: https://javascript.info/static-properties-methods这里有一篇文章可以解释这个概念: https : //javascript.info/static-properties-methods
seidme's answer is also solid. seidme的回答也很可靠。
Original原来的
Static methods are represented as global variables (I think?) in the Angular application, so I think they would only be instantiated once each.静态方法在 Angular 应用程序中表示为全局变量(我认为?),所以我认为它们每个只会被实例化一次。 Therefore I think it would not have a large impact on performance (relative to an instantiation of the class for each component that needs it.)因此,我认为它不会对性能产生很大影响(相对于需要它的每个组件的类的实例化。)
I use static when I don't want to inject the service and get an instance just to leverage context-agnostic formatting/utility methods.当我不想注入服务并获取实例只是为了利用与上下文无关的格式/实用程序方法时,我使用静态。 Application-wide versions of these don't seem unreasonable to me.这些应用程序范围的版本对我来说似乎并不合理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.