它说this.draw没有定义,但是我在同一个类中定义了draw。为什么我不能在另一个类函数中调用一个类函数?
function Recorder() {
this.recording = false;
this.sideLength = 5;
this.currList = new SLinkedList(comparator);
this.curr = null;
}
Recorder.prototype = {
constructor:Recorder,
draw : function (xPos, yPos) {
if(recording) {
currList.addEnd([xPos,yPos]);
}
let context = document.getElementById("canvas").getContext("2d");
let getColorPickerByID = document.getElementById("colors");
let getValueOfColorPicker = getColorPickerByID.options[getColorPickerByID.selectedIndex].text;
context.fillStyle = getValueOfColorPicker;
context.fillRect(xPos,yPos,sideLength,sideLength);
},
processMousePosition : function (evt){
this.draw(evt.pageX, evt.pageY);
}
};
答案 0 :(得分:1)
给您的类一个名为handleEvent
的方法。使此函数检查evt.type
并为该事件调用适当的方法。
function Recorder() {
this.recording = false;
this.sideLength = 5;
this.currList = new SLinkedList(comparator);
this.curr = null;
}
Recorder.prototype = {
constructor:Recorder,
handleEvent : function(evt) {
switch (evt.type) {
case "mousemove":
this.processMousePosition(evt);
break;
}
},
draw : function (xPos, yPos) {
// your draw code
},
processMousePosition : function (evt){
this.draw(evt.pageX, evt.pageY);
}
};
然后,当您将侦听器添加到元素时,传递Recorder
的实例而不是其方法。这将导致事件发生时调用handleEvent
方法。
var r = new Recorder();
myElement.addEventListener("mousemove", r);