Private class fields is a feature added in ES6 that allows you to declare private properties in a class. These properties cannot be accessed from outside the class or subclass.
To define a private class field in javascript, you can use the #
symbol before the property name, like this:
index.tsx98 chars8 lines
In the example above, #privateField
is a private field that can only be accessed within the scope of the MyClass
class.
To access the private field from within the class, you can define a method that returns the value of the private field, like the getPrivateField()
method above.
index.tsx201 chars4 lines
However, if you try to access the private field directly from outside the class, you will get a SyntaxError
.
Private class fields provide a way to encapsulate data within a class, and prevent outside code from accessing or modifying it directly. This improves the overall robustness and maintainability of your JavaScript code.
gistlibby LogSnag