Composition is a useful alternative to inheritance when one wants to cascade method calls from child to parent, see child extended class method calls its super version but that still only sees child data
However, for the child to present an interface that is compatible with parent type, one must implement a potentially large number of stub methods that all have the same form, namely they just relay the call to the former parent (which is now a component).
My question here, is it possible to write a catch-all method? A catch-all method would be called when none of the other methods are called. The catch-all would then just relay calls to the parent component. Thus the stub would only have to be written once. Variations could be used to sort multiple inheritance, etc.
Something like this:
class A {
constructor(){
this.x = "super x!";
}
f(){
console.log("I am a super f()!");
}
logx(){
this.f();
console.log(this.x);
}
}
class B {
constructor(){
this.a = new A();
this.x = "derived x.";
}
f(){
console.log("I am a derived f()");
}
logx(){
this.a.logx();
}
}
let b = new B;
b.logx();
I am a super f()!
super x!
Hypothetically would instead be something like this:
class A {
constructor(){
this.x = "super x!";
}
f(){
console.log("I am a super f()!");
}
logx(){
this.f();
console.log(this.x);
}
}
class B {
constructor(){
this.a = new A();
this.x = "derived x.";
}
f(){
console.log("I am a derived f()");
}
catch_all(method_name, ...args){
this.a.method_name(...args);
}
}
let b = new B;
b.logx();
I am a super f()!
super x!