Reputation: 1899
Angular 5
Why does only a variable qualified with an access modifier, in a constructor's signature, get recognized throughout a class?
For eg.
constructor(private n: number) {
}
fn(){
this.n = 6; //Allowed
}
but
constructor(n: number) {
}
fn(){
this.n = 6; //Not allowed
}
Upvotes: 4
Views: 1713
Reputation: 1723
Because, when you define a constructor with the input parameter which is marked with private (or public) access modifier (from Typescript) it tells to your class to create that property and make the assignment. The following examples do the same thing:
constructor(public a, private b) {}
public a;
private b;
constructor(a, b) {
// a and b are locally scoped to this constructor method, and
// are not the same as the property methods this.a and this.b,
// so they need to be assigned in order to be accessible in the class
this.a = a;
this.b = b;
}
When you do it without access modifier (which is local to the constructor function only), you need to then define that class property by yourself as in the second example.
More about that you may read on that pages to understand it well:
And, here is the same question with useful answers:
Upvotes: 6
Reputation:
Simple variable scoping.
When you write
constructor(x) {}
x
can only be accessed within the constrcutor.
With an access modifier, you can define it as a class member, hence changing the scope to the class.
Upvotes: 9