Starting with ES13/ES2022, you can make any static class method private by prefixing the method name with #
(hash symbol).
For example:
// ES13+
class Foo {
static publicMethod() {
return Foo.#privateMethod();
}
static #privateMethod() {
return 'foobar';
}
}
console.log(Foo.publicMethod()); // 'foobar'
// SyntaxError
console.log(Foo.#privateMethod);
Similarly, you can make static getter, setter, generator, async, or async generator methods private as well:
// ES13+ class MyClass { static #privateMethod() {} static * #privateGeneratorMethod() {} static async #privateAsyncMethod() {} static async * #privateAsyncGeneratorMethod() {} static get #privateGetter() {} static set #privateSetter(value) {} }
Private static methods are only accessible:
- On the class itself (e.g.
MyClass.staticMethod()
), and; - When using
this
in static methods.
One important limitation to understand is that, if a static method in a base class accesses a private static method (or field) within that class using the this
context, and you try to access this method from a subclass, a TypeError
will be thrown:
class BaseClass {
static #privateStaticMethod() {
return 'foo';
}
static baseStaticMethod1() {
return BaseClass.#privateStaticMethod();
}
static baseStaticMethod2() {
return this.#privateStaticMethod();
}
}
class SubClass extends BaseClass {}
console.log(SubClass.baseStaticMethod1()); // 'foo'
// TypeError: Receiver must be class BaseClass
console.log(SubClass.baseStaticMethod2());
In addition to declaring static methods as private, you can also:
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.