1

I'm trying to create a parent class A with a private field #abc and a subclass B that overrides this field. However, when I call methods from the parent class that access the private field, it still uses the parent class's #abc instead of the subclass's #abc.

class A {
  #abc = 'hello from a';
  
  hellos() {
    console.log(this.#abc);
  }
  
  getHellos() {
    console.log(this.#abcd);
  }
  
  get #abcd() {
    return this.#abc;
  }
}

class B extends A {
  #abc = 'hello from b';
  
  get #abcd() {
    return this.#abc;
  }
}

const b = new B();
b.hellos();       // Expect 'hello from b', but get 'hello from a'
b.getHellos();    // Expect 'hello from b', but get 'hello from a'

Why does the private field #abc in A not get overridden by the private field #abc in B? How can I achieve the desired behavior where the subclass's private field is used instead?

Is there a better way to design this so that the behavior works as expected?

1 Answer 1

1

In JavaScript, private fields with the # symbol are class-specific and don't work like traditional inheritance. When a subclass extends a parent class, it creates its own separate private field, not overriding the parent's. Here's a better way to handle this:

class A {
  #abc = 'hello from a';
  
  hellos() {
    console.log(this.getValue());
  }
  
  getValue() {
    return this.#abc;
  }
}

class B extends A {
  #abc = 'hello from b';
  
  getValue() {
    return this.#abc;
  }
}

const b = new B();
b.hellos();  // Now logs 'hello from b'

This approach allows each class to define its own behavior while maintaining the expected inheritance pattern.

Sign up to request clarification or add additional context in comments.

2 Comments

thank. that make the #abc readonly . And I think is good enough but forgot to set getValue in the extended class can lead it to headache, because it work just not as expected. we can solve that by define getValue(){ throw 'must be implemneted'} in class A
A.prototype.getValue.call(new B) still returns “hello from a”, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.