rahs
rahs

Reputation: 1899

Constructor parameter with access modifier vs without access modifier w.r.t access throughout class

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

Answers (2)

severus256
severus256

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:

Classes in Typescript

And, here is the same question with useful answers:

CLICK

Upvotes: 6

user4676340
user4676340

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

Related Questions