While refactoring a piece of code, I came across a class that I want to replace with a generic one. Hence, it should have pretty much the same functionality, but according to a "type" argument.
In order to ensure backward compatibility I don't want to just create a new class, but to keep the initialisations of the older one.
However I'm not sure how to implement this structure in JavaScript:
class Generic {
constructor(type, data) {
this.type = type;
this.data = data;
}
action() {
switch(this.type) {
// Does things dynamically, depending on `this.type`
case 'old': return `old: ${this.data}`;
default: return this.data;
}
}
}
class Old {
constructor(data) {
// I want this to be equivalent to:
// new Generic('old', data);
}
}
// So this should work seamlessly
const foo = new Old('Hello');
const output = foo.action();
console.log(output);