13

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?

4
  • extends is per-class and not per-instance. What do you want to achieve? Commented Sep 15, 2017 at 17:00
  • Adjusted my request to only say "child-specific", ignore my use of "instance" @ideaboxer Commented Sep 15, 2017 at 17:02
  • sets up this.elem should happen after the super() call... Commented Sep 15, 2017 at 17:04
  • could you give a real life example? this might be an xy problem... Commented Sep 15, 2017 at 17:09

1 Answer 1

20

You can use super in methods:

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

this in child class and in parent class is the same thing, and refers to the actual object, so if you call a method in parent's code, it will call child's implementation, if it is indeed a child. Same works in other languages, for example Python and Ruby.

Working code:

class Parent {
  constructor(elem) {
    this.elem = elem
    this.elem.addEventListener('click', (e) => { this.doSomething(e) })
  }

  doSomething(e) {
    alert('doing something')
  }
}

class Child extends Parent {
  constructor(elem) {
    super(elem)
  }

  doSomething(e) {
    super.doSomething(e)
    alert('doing another something')
  }
}

let child = new Child(document.getElementById('button'))
<button id="button">Alert</button>

Sign up to request clarification or add additional context in comments.

2 Comments

super.doSomething(e) is called by an event listener in my example. I want to use the super's event listener to trigger the child's method as a callback – or at least afterwards. This implementation seemingly only calls the super's method in a from a different method, causing me to reestablish the event listening in the child.
yea this actually worked perfectly. For some reason I assumed super.doSomething(e) would have been called without the context of the parent.

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.