Javascript-Private methods
The public equivalent and private static methods are return on the class itself, not instances of the class. Like private static fields, they are only provided to access from inside the class declaration.
Private static methods are generator, async, and async generator functions.
class ClassWithPrivateStaticMethod {
static #privateStaticMethod() {
return 42
}
static publicStaticMethod1() {
return ClassWithPrivateStaticMethod.#privateStaticMethod();
}
static publicStaticMethod2() {
return this.#privateStaticMethod();
}
}
console.assert(ClassWithPrivateStaticMethod.publicStaticMethod1() === 42);
console.assert(ClassWithPrivateStaticMethod.publicStaticMethod2() === 42);
This can lead to unexpected behavior when calling this keyword. In the following example, this keyword refers to the Derived class when we try to call.
Derived.publicStaticMethod2(), and thus display the same “provenance restriction” as mentioned above:
class Base {
static #privateStaticMethod() {
return 42;
}
static publicStaticMethod1() {
return Base.#privateStaticMethod();
}
static publicStaticMethod2() {
return this.#privateStaticMethod();
}
}
class Derived extends Base {}
console.log(Derived.publicStaticMethod1()); // 42
console.log(Derived.publicStaticMethod2()); // TypeError
Private instance methods:
Private instance methods are called methods available on class instances whose accessibility is restricted in the same manner as private instance fields.
class ClassWithPrivateMethod {
#privateMethod() {
return 'hello world'
}
getPrivateMessage() {
return this.#privateMethod()
}
}
const instance = new ClassWithPrivateMethod()
console.log(instance.getPrivateMessage())
// expected output: "hello world"
Private instance methods are maybe generator, async, or async generator functions. Private getters and setters are also possible:
class ClassWithPrivateAccessor {
#message
get #decoratedMessage() {
return `✨${this.#message}✨`
}
set #decoratedMessage(msg) {
this.#message = msg
}
constructor() {
this.#decoratedMessage = 'hello world'
console.log(this.#decoratedMessage)
}
}
new ClassWithPrivateAccessor();
// expected output: "✨hello world✨"