Starting with ES13/ES2022, you can make static fields/members in a class private by prefixing the field name with #
(hash symbol).
For example:
// ES13+
class Foo {
static PUBLIC_PROP = 321;
static #PRIVATE_PROP = 123;
}
console.log(Foo.PUBLIC_PROP); // 321
// SyntaxError
console.log(Foo.#PRIVATE_PROP);
Private static fields are only accessible on:
- On the class itself (e.g.
MyClass.staticField
), 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 field (or method) 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 #PRIVATE_STATIC_FIELD;
static baseStaticMethod1() {
BaseClass.#PRIVATE_STATIC_FIELD = 'foo';
return BaseClass.#PRIVATE_STATIC_FIELD;
}
static baseStaticMethod2() {
this.#PRIVATE_STATIC_FIELD = 'foo';
return this.#PRIVATE_STATIC_FIELD;
}
}
class SubClass extends BaseClass {}
console.log(SubClass.baseStaticMethod1()); // 'foo'
// TypeError: Cannot write private member #PRIVATE_STATIC_FIELD to an object whose class did not declare it
console.log(SubClass.baseStaticMethod2());
In addition to declaring static fields 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.