Why is access to private static members through a subclass forbidden?

458 Views Asked by At

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, this refers to the Subclass class (not the ClassWithPrivateStaticField class) when we try to call Subclass.publicStaticMethod(), and so causes a TypeError.

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?

1

There are 1 best solutions below

19
Bergi On

On the contrary, private instance fields are inherited

No, they aren't either. Private fields are not inherited prototypically, accessing them does not follow the prototype chain.

The difference between static and instance fields is that the latter are created by the constructor, which is "inherited", so they are also created on subclass instances by default (in the super() call). There is no equivalent feature for static properties, no code from the parent class runs (and could create private static fields) when a child class extends it.