0

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);

1 Answer 1

1

You could extend Generic:

  class Old extends Generic {
    constructor() {
       super("old");
   }
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.