Home > Mobile >  Method substitution between objects
Method substitution between objects

Time:12-22

In nodejs, typescript, I want to substitute a method of an object with a method of another object; I have written the following very simple example to better understand my problem (the real situation is, more or less, the same):

export default class A_01 {
  constructor(private variableA1: string) {}

  public writeSomething() {
    console.log(`${this.variableA1} from class A`);
  }
}
import A_01 from "./oop_class_A";

export default class B_01 extends A_01 {
  constructor(private variableB1: string) {
    super(variableB1);
  }

  public writeSomething() {
    console.log(`${this.variableB1} from class B`);
  }
}
import A_01 from "./oop_class_A";
class C_01 {
  constructor() {}

  run() {
    return new A_01("Object A_01 from class C_01"); // cannot modify this object creation!!!
  }
}
import A_01 from "./oop_class_A";
import B_01 from "./oop_class_B";

const D_01 = new A_01("from_class_D_01");

D_01.writeSomething();

So, how to print from_class_D_01 from class B (and NOT from class A) ?
I have tried casting

const D_01 = new A_01("from_class_D_01") as B_01

but it's only a type and I lose it at runtime.

CodePudding user response:

Not sure if this is what you need, this is a very hacky way to overwrite the writeSomething method after an A_01 instance has been created.

const D_01 = new A_01("from_class_D_01")
D_01.writeSomething = B_01.prototype.writeSomething
D_01.writeSomething()

Now it will write "from class B" even though it's an instance of A_01

  • Related