Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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';
like image 640
runtimeZero Avatar asked Aug 05 '16 21:08

runtimeZero


People also ask

What is the difference between a public and a private variable declaration in a class?

A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member. A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.

What is difference between private and public in TypeScript?

TypeScript provides three access modifiers to class properties and methods: private , protected , and public . The private modifier allows access within the same class. The protected modifier allows access within the same class and subclasses. The public modifier allows access from any location.

What is the difference between public and private variables?

Public variables, are variables that are visible to all classes. Private variables, are variables that are visible only to the class to which they belong.

Is public necessary in TypeScript?

If you want to use the shorthand initialization feature TypeScript adds to class constructors, you need the public to tell TypeScript to do that.


1 Answers

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.

like image 171
Ryan Cavanaugh Avatar answered Nov 15 '22 08:11

Ryan Cavanaugh