Natalie Weizenbaum
Natalie Weizenbaum

Reputation: 5974

Why can't I set a private field in a function called from a superclass constructor?

When I run the following code in Node.js:

class Superclass {
  constructor() {
    this.setPrivateField();
  }

  setPrivateField() {
    // No implementation
  }
}

class Subclass extends Superclass {
  #field;
  setPrivateField() {
    console.log(this);
    this.#field = 1;
  }
}

new Subclass();

it prints:

Subclass {}
test.js:16
    this.#field = 1;
                ^

TypeError: Cannot write private member #field to an object whose class did not declare it
    at Subclass.setPrivateField (test.js:16:17)
    at new Superclass (test.js:5:10)
    at new Subclass (test.js:12:1)
    at Object.<anonymous> (test.js:20:1)
    at Module._compile (node:internal/modules/cjs/loader:1434:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1518:10)
    at Module.load (node:internal/modules/cjs/loader:1249:32)
    at Module._load (node:internal/modules/cjs/loader:1065:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:158:12)
    at node:internal/main/run_main_module:30:49

Node.js v22.2.0

This doesn't make sense to me. The field is declared in Subclass, and the type of the object it's being assigned to is confirmed to be Subclass. What's going on? It seems like a bug in V8, although I've confirmed that the same behavior happens in Firefox as well.

Upvotes: 1

Views: 41

Answers (0)

Related Questions