In JavaScript, there is no built-in support for private properties, but you can simulate them using symbols or underscore convention. Symbols are a new primitive type added in ECMAScript 6 that can be used as unique identifiers. Here's an example of how to create a private property using symbols:
index.tsx197 chars12 lines
In the example above, we use a symbol _privateProperty
to create a private property in the class MyClass
. The property is initialized in the constructor and can only be accessed using the getPrivateProperty()
method.
Alternatively, you can use the underscore prefix convention to indicate that a property or method is private:
index.tsx142 chars10 lines
In the example above, we use the underscore prefix to indicate that _privateProperty
is a private property in the class MyClass
. However, this convention is not enforced by the language, and the property can still be accessed from outside the class.
gistlibby LogSnag