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';
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.
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.
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.
If you want to use the shorthand initialization feature TypeScript adds to class constructors, you need the public to tell TypeScript to do that.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With