Reputation: 8307
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?
Upvotes: 1
Views: 35
Reputation: 81
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.
Upvotes: 1