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?
You can use
super
in methods: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: