runtimeZero
runtimeZero

Reputation: 28086

Typescript: Difference between declaring class variables using private, public and nothing

What's the difference between:

A.
class foo {
  bar: string;
}

B.
class foo {
  private bar: string;
}

C.
class foo {
  public bar: string;
}

Apparently i was able to access "bar" in all three cases using the following:

var temp = new foo();
temp.bar = 'abc';

Upvotes: 6

Views: 907

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220964

bar: string is 100% equivalent to public bar: string. The default accessibility modifier is public.

private is compile-time privacy only; there is no runtime enforcement of this and the emitted code is identical regardless of the access modifier. You'll see an error from TypeScript when trying to access the property from outside the class.

You could also have said protected, which is like private except that derived classes may also access the member. Again, there's no difference in the emitted JavaScript here.

Upvotes: 6

Related Questions