🥦Private class fields
A private class field is a class member (a field or a method) that can only be accessed from within the class. It is declared directly in the class, rather than inside a method.
Private class fields are prefixed with a #
symbol.
Here is an example of a class with a private field:
In this example, the Counter
class has a private field called #count
and public methods increment
and getCount
. The private #count
field is used to store the current count, and can only be accessed and modified from within the class. The public increment
method is used to increase the count by 1, and the public getCount
method is used to get the current count.
Private fields and methods can be useful for encapsulation, as they allow you to hide implementation details and prevent direct modification of sensitive data.
Private class fields and methods are a relatively new feature in JavaScript, and are currently only supported in certain modern browsers and when using certain language transpilers (such as Babel).
Last updated