Issue
I am learning Angular2
and working with classes
in javascript
first time.
What does the private
parameter and why it couldn't be simply heroService: HeroService
?
constructor(private heroService: HeroService) { }
Solution
Looks like a parameter property. Basically, adding an access modifier (public/private/protected/readonly) to a constructor parameter will automatically assign that parameter to a field of the same name.
Specifically, from those docs:
TypeScript offers special syntax for turning a constructor parameter into a class property with the same name and value. These are called parameter properties and are created by prefixing a constructor argument with one of the visibility modifiers public, private, protected, or readonly. The resulting field gets those modifier(s)
So the following are equivalent:
class Foo {
private bar: string;
constructor(bar: string) {
this.bar = bar;
}
}
class Foo {
constructor(private bar: string) {}
}
Answered By - CRice
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.