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?
The syntax to extend another class is: class Child extends Parent . Let's create class Rabbit that inherits from Animal : class Rabbit extends Animal { hide() { alert(`${this.name} hides!`); } } let rabbit = new Rabbit("White Rabbit"); rabbit. run(5); // White Rabbit runs with speed 5.
You just have to create an object of the child class and call the function of the parent class using dot(.)
Inheritance concept is to inherit properties from one class to another but not vice versa. But since parent class reference variable points to sub class objects. So it is possible to access child class properties by parent class object if only the down casting is allowed or possible....
Definition and UsageThe extends keyword is used to create a child class of another class (parent). The child class inherits all the methods from another class. Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create a new class.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With