From MDN Web Docs:
There is a restriction on private static fields: only the class which defines the private static field can access the field. This can lead to unexpected behavior when using
this. In the following example,thisrefers to theSubclassclass (not theClassWithPrivateStaticFieldclass) when we try to callSubclass.publicStaticMethod(), and so causes aTypeError.class ClassWithPrivateStaticField { static #privateStaticField = 42; static publicStaticMethod() { return this.#privateStaticField; } } class Subclass extends ClassWithPrivateStaticField {} Subclass.publicStaticMethod(); // TypeError: Cannot read private member #privateStaticField from an // object whose class did not declare it[…]
You are advised to always access private static fields through the class name, not through
this, so inheritance doesn’t break the method.
So this cannot be used in static methods to access private static members (the example for fields above also applies to methods) because it breaks for subclasses.
However this can be used in instance methods to access private instance members (the example for fields below also applies to methods) because it works for subclass instances:
class ClassWithPrivateInstanceField {
#privateInstanceField = 42;
publicInstanceMethod() {
return this.#privateInstanceField;
}
}
class Subclass extends ClassWithPrivateInstanceField {}
new Subclass().publicInstanceMethod(); // 42
Why is access to private static members through a subclass forbidden?