Extending parent class methods in child class in Javascript ES6

Viewed 6669

I want to extend a child's functionality of a specific method in a parent class. I'm still getting used to OOP in ES6 so I'm not sure if this is possible or breaks rules.

I'm looking for something like this:

class Parent {
  constructor(elem) {
    this.elem = elem;

    elem.addEventListener((e) => {
      this.doSomething(e);
    });
  }

  doSomething(e) {
    console.log('doing something', e);
  }
}

class Child extends Parent {
  constructor(elem) {
    // sets up this.elem, event listener, and initial definition of doSomething
    super(elem)
  }

  doSomething(e) {
    // first does console.log('doing something', e);
    console.log('doing another something', e);
  }
}

In essence I want to append a child-specific callback on a parent method. Is there a creative way of doing this without creating a completely new class with the same functionality?

1 Answers
Related