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

标签 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);
  }

};

最佳答案

为您的类提供一个名为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);

关于javascript - 为什么我不能在 Javascript 中的同一个类函数中调用一个类函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55526903/

相关文章:

javascript - PHPStorm 上的 JSX 语法错误

javascript - MongoDB : multiple indexes or multiple collections 哪个更好

javascript - 从 JSON 替换字符串

php - 如何使用 td 中的 onclick 事件添加表格行

javascript - undefined reference - jQuery 选择器与 JavaScript 变量

javascript - 如何从 Node.js 文档中获取表格

javascript - 如何通过图像预览多次显示文件输入按钮?

javascript - 从数组末尾开始查找indexof值

javascript - 当 javascript 值插入到 .net 文本框时,document.getElementsByName(...)[0] 未定义

javascript - BackboneJS 重置模型