我有一个自定义类,它是为各种目的而扩展的,下面的代码工作得很好:
class Inator {
constructor(whichCanvas) {
this.myCanvas = whichCanvas;
}
}
class Ballgowninator extends Inator {
constructor(whichCanvas) {
super(whichCanvas);
this.myCanvas.addEventListener("mousedown",this.handleMouseDown);
this.myCanvas.addEventListener("mouseup",this.handleMouseUp);
}
handleMouseDown(e) {
alert("ballgowninator mousedown");
}
handleMouseUp(e) {
alert("ballgowninator mouseup");
}
}
class Yodelinator extends Inator {
constructor(whichCanvas) {
super(whichCanvas);
this.myCanvas.addEventListener("mousedown",this.handleMouseDown);
this.myCanvas.addEventListener("mouseup",this.handleMouseUp);
}
handleMouseDown(e) {
alert("yodelinator mousedown");
}
handleMouseUp(e) {
alert("yodelinator mouseup");
}
}
(mousedown和mouseup只是两个例子;我希望能够处理其他鼠标事件,甚至键盘事件。)
有没有方法可以将这些重复的代码移动到
Inator
超类?我假设super中的eventListener无法引用子类中的函数。
编辑:在本例中,虽然事件处理程序非常相似,但实际上,事件处理方式可能非常不同,甚至被忽略。
谢谢!