If I do something like this below, how can I access the property out the class?
class Person
{
private static name: string;
}
console.log(Person.name);
Shouldn't it inaccessible?
It should be an error but isn't. From the spec, section 8.2.1:
It is not possible to specify the accessibility of statics—they are effectively always public.
Accessibility modifiers on statics are something the team has considered in the past. If you have a strong use case you should bring this up on codeplex site!
class Person
{
private static theName: string = "John";
static get name():string{
return Person.theName;
}
}
console.log(Person.name);
If a static property is private we need to provide a static get method to access it. This may not be a common solution but it is the only way I know of to directly access a private static property. On the other hand, you may have to add a second get method if you also intend to access the property from an instantiated object. Both get methods can have the same name since the static get method will be invisible to the instantiated object.
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