runtimeZero runtimeZero - 1 year ago 239
TypeScript Question

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

What's the difference between:

class foo {
bar: string;

class foo {
private bar: string;

class foo {
public bar: string;

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download