super
doSomething(e) {
super.doSomething(e)
console.log('doing another something', e)
}
this
在子类和父类中是同一件事,并且指的是实际的对象,所以如果你在父类的代码中调用一个方法,它将调用子类的实现,如果它确实是子类的话。这在其他语言中也适用,例如Python和Ruby。
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>