Javascript private class functions
Today I learned that you can make a class function to be private by prefixing it with a #
. Check this out:
class MyClass {
myPublicFunc() {
console.log("=> hey myPublicFunc");
this.#myPrivateFunc();
}
#myPrivateFunc() {
console.log("=> hey myPrivateFunc");
}
}
const myClass = new MyClass();
myClass.myPublicFunc();
// => hey myPublicFunc
// => hey myPrivateFunc
myClass.#myPrivateFunc();
// Uncaught SyntaxError:
// Private field '#myPrivateFunc' must be declared in an enclosing class
We can also use that trick to make static methods, fields or static fields as well.
Thanks Andrew Vogel for this tip 😁
Tweet