Junior — Middle
Is it possible, when using encapsulation, to make only fields accessible and hide the rest?
sobes.tech AI
Answer from AI
In JavaScript (Node.js), encapsulation is usually achieved using private fields and class methods. However, making only fields accessible and hiding methods directly is not possible, as methods are typically part of the object and accessible if they are public.
But you can make fields public and methods private by using the syntax for private fields and methods (starting with #), for example:
class Example {
publicField = 42; // public field
#privateMethod() { // private method
console.log('Hidden method');
}
callPrivate() {
this.#privateMethod();
}
}
const obj = new Example();
console.log(obj.publicField); // 42
// obj.#privateMethod(); // Error, method is not accessible
Thus, fields can be accessed directly, and methods are hidden. But remember that public methods are part of the class interface and are usually made accessible for interaction with the object.