When it comes to developing APIs, self-documenting code is very important, as it simplifies the user’s effort in filtering the information they need. If it’s clearly visible which parts are public and which parts are private, understanding the big picture of the API becomes much easier.
In modern JavaScript, we can use classes with true private methods to encapsulate logic cleanly.
This approach provides clear visibility:
- Methods prefixed with
#
(like#myPrivateMethod1
) are private to the class. - Public methods (like
myPublicMethod1
) are accessible from outside the class and act as the API surface.
This pattern avoids legacy patterns like closures or pseudo-class systems (e.g., Class.extend()
), and improves maintainability by using native language features.
class MyClass {
constructor(settings) {
// Clone settings (deep copy)
this.settings = JSON.parse(JSON.stringify(settings));
}
#myPrivateMethod1(param1) {
console.log(this.settings.param1);
}
myPublicMethod1() {
// Call private method
this.#myPrivateMethod1();
}
}
// Usage
const myObject = new MyClass({
param1: 'abcdef'
});
myObject.myPublicMethod1();