I'm learning JavaScript and NodeJS as I go for a work project and have been making heavy use of ES6 classes over ProtoTypes. I would like to use private methods or something like private methods, but it seems like this is not a feature of JavaScript classes yet. Are there any common patterns for this with ES6 classes? So far I've devised this mess of a strategy:
class Private {
constructor(pub) {
this.pub = pub;
this.privateAttribute = "Private Attribute\n";
}
privateMethod() {
process.stdout.write('Private Method\n');
}
privateMethodCallsPublicMethod() {
this.pub.publicMethod();
}
privateMethodUsesPublicAttribute() {
process.stdout.write(this.pub.publicAttribute);
}
}
class aClass {
#private = new Private(this);
constructor() {
this.publicAttribute = "Public Attribute\n";
}
publicMethod() {
process.stdout.write('Public Method\n')
}
publicMethodCallsPrivateMethod() {
this.#private.privateMethod();
}
publicMethodUsesPrivateAttribute() {
process.stdout.write(this.#private.privateAttribute);
}
privateMethodsHaveAccessToPublicMethods() {
this.#private.privateMethodCallsPublicMethod();
}
privateMethodsHaveAccessToPublicAttributes() {
this.#private.privateMethodUsesPublicAttribute();
}
}
module.exports = { aClass };
as well as
class aClass {
#privateAttribute = "Private Attribute\n";
constructor() {
this.publicAttribute = "Public Attribute\n";
}
publicMethod() {
process.stdout.write('Public Method Called\n');
}
#privateMethod = () => {
process.stdout.write('Private Method Called\n');
}
publicMethodCallsPrivateMethod() {
this.#privateMethod();
}
publicMethodUsesPrivateAttribute() {
process.stdout.write(this.#privateAttribute);
}
#privateMethodCallsPublicMethod = () => {
this.publicMethod();
}
}
module.exports = { aClass };
But I'm pretty new to JavaScript and don't know how these work in terms of:
- The lexical this, especially scoping
- Implications on memory allocation and performance
- Readability for JavaScripters
Not to mention it just doesn't look nice. I wouldn't mind learning ProtoTypes if need be, I actually like the way things separate (I program mostly in Rust and C so mentally I don't usually think in Classes), but I'd like to be writing "Modern JavaScript" and more importantly readable, familiar JavaScript if possible and I just have no instinct for what that looks like.