In this blog post, we’ll explore the introduction of private class fields in JavaScript and how they can be used to enforce private properties within a class.
Before the availability of private class fields, developers would rely on naming conventions to indicate that a property is intended to be private. For example, prefixing the property with an underscore (_
) was commonly used. However, these conventions were not strictly enforced and the private properties could still be accessed from outside the class.
class Counter {
_count = 0;
increment() {
this._count++;
}
}
With the introduction of private class fields, we now have a more robust way to enforce privacy within a class.
class Counter {
#count = 0;
increment() {
this.#count++;
}
}
In the updated example, the #count
field is marked as private using the #
symbol. Attempts to access this private field from the outside will now result in a syntax error, ensuring that the encapsulation is maintained.
It’s worth noting that private class fields are part of the new class fields proposal and are currently supported in Chrome 72 and Node 12 onwards.
With the introduction of private class fields, JavaScript developers can now confidently enforce the encapsulation of private properties within their classes, leading to more robust and maintainable code.