In JavaScript, we can achieve encapsulation and protected properties in classes using Symbols. Symbols have a unique identifier and can be used as a property key on objects. We can create a symbol as a private property and then define a getter method to access the property value.
Here's an example:
index.tsx344 chars19 lines
In the above example, we create a Symbol _salary
and use it to define the protected property in the Employee
class. We can access the protected property using the getSalary()
method. And when we try to access it directly, it returns undefined
.
Note that this is not truly private, as someone could simply access the protected property by doing Object.getOwnPropertySymbols(john)[0]
, but it does provide a level of protection against accidental or unknowing manipulation of the property.
gistlibby LogSnag