Extending Parent Class Methods In Child Class In Javascript Es6
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 looki
Solution 1:
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:
classParent {
constructor(elem) {
this.elem = elem
this.elem.addEventListener('click', (e) => { this.doSomething(e) })
}
doSomething(e) {
alert('doing something')
}
}
classChildextendsParent {
constructor(elem) {
super(elem)
}
doSomething(e) {
super.doSomething(e)
alert('doing another something')
}
}
let child = newChild(document.getElementById('button'))
<buttonid="button">Alert</button>
Post a Comment for "Extending Parent Class Methods In Child Class In Javascript Es6"