In Angular Components, written in typescript, it is possible to declare a class member (variable) as parameter of the constructor. My question is about why to do so.
To make myself clear, see the snippets below. Both have identical meaning.
- The first is the classic way to define a private member using dependency injection mechanism (as it is done in most OO languages).
- The latter is, if I'm not mistaken, a specificity of TypeScript.
export class HeroListComponent implements OnInit {
// private member declaration
private heroService:HeroService;
// constructor signature
constructor(service:HeroService) {
// private member assignment
this.heroService = service;
}
}
export class HeroListComponent implements OnInit {
// here the private member is declared inside the constructor signature
constructor(private heroService:HeroService) { }
}
In my opinion, the first syntax is clearer and easier to understand for people unfamiliar with TypeScript.
So, I was wondering if there is any particular reason, apart from being shorter (which does not really matters since the code will eventually be minified/uglyfied), to use the latter. Thanks.