问题
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:
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>
来源:https://stackoverflow.com/questions/46244417/extending-parent-class-methods-in-child-class-in-javascript-es6