👋 The following examples use access modifiers from TypeScript, but I think the question should also be relevant for JavaScript developers. Let's say I have some parent class, where I define some necessary members and an implementation of a shared method:
// ParentClass.ts
export default class ParentClass {
private static voo;
private bar;
constructor(bar) {
this.bar = bar;
}
private commonMethod(baz) {
doSomething(ParentClass.voo);
doSomethingElse(this.bar, baz);
}
}
And then I have some child class, that inherits this behavior:
// ChildClass.ts
export default class ChildClass extends ParentClass {
voo = "Jake";
constructor(bar) {
super(bar)
}
public uniqueMethod(ter) {
doAnotherThing(this.bar);
this.commonMethod(ter);
}
}
Of course, when I call commonMethod() inside of ChildClass.uniqueMethod(), it will reference the value of ParentClass.voo, which is undefined. What I would like to happen is that each inheriting child class uses the exact same implementation of that method, but it references the static member of the child class itself. So when I call ChildClass.uniqueMethod(), commonMethod() will use the value from ChildClass.voo() rather than the parent equivalent.
One sidesteps this issue entirely by just making voo an instance member, rather than a static member, but let's say that you have some scenario where a static voo is more useful in other ways.
Is such a solution readily available? I've posted the solution that I'm currently using as a reply to this question, but I can't help but think there's a more direct solution out there.
This is what I currently have, where I'm attaching an instance accessor, and adjusting the commonMethod() to use that accessor:
// ParentClass.ts
export default class ParentClass {
private static _voo;
private bar;
constructor(bar) {
this.bar = bar;
}
public get voo() {
return ParentClass._voo;
}
private commonMethod(baz) {
doSomething(this.voo);
doSomethingElse(this.bar, baz);
}
}
And then inheriting classes override that accessor:
// ChildClass.ts
export default class ChildClass extends ParentClass {
_voo = "Jake";
constructor(bar) {
super(bar)
}
public override get voo(){
return ChildClass._voo
}
public uniqueMethod(ter) {
doAnotherThing(this.bar);
this.commonMethod(ter);
}
}
This route doesn't seem very elegant to me, so I'd be very interested to hear feedback or suggestions about better ways to do this.