为什么我不能在Javascript的同一类函数中调用类函数?

时间:2019-04-05 01:02:48

标签: javascript

它说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);
  }

};

1 个答案:

答案 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);