javascript - 尝试访问原型(prototype)方法中的成员变量

标签 javascript prototype

我是第一个在 js 中使用 OOP 风格的人,这个范围让我很困惑。

$(document).ready(function() {
  $("#cv").attr({
    width: '860px',
    height: '645px'
  });
  var ctx = new Blackboard($("#cv"));
});

function Blackboard(canvas) {
  this.canvas = canvas;
  this.ctx = this.canvas.get(0).getContext("2d");
  this.drawing = false;
  this.canvas.on('mousedown', this.press);
  this.canvas.on('mousemove', this.move);
  this.canvas.on('mouseup', this.end);
  this.setShape();
}

Blackboard.prototype.setShape = function(color, width) {
  this.color = 'white';
  this.width = 1;
  if (color != null) {
    this.color = color;
  }
  if (width != null) {
    this.width = width;
  }
  this.ctx.strokeStyle = this.color;
  this.ctx.lineWidth = this.width;
}

Blackboard.prototype.press = function(event) {
  console.log(this.ctx); // undefined!
  this.ctx.beginPath();
  this.ctx.moveTo(event.pageX, event.pageY);
  this.drawing = true;
}

Blackboard.prototype.move = function(event) {
  if (this.drawing) {
    this.ctx.lineTo(event.pageX, event.pageY);
    this.ctx.stroke();
  }
}

Blackboard.prototype.end = function(event) {
  this.drawing = false;
}

$("#cv")是 Canvas 元素。

正如我在评论中提到的,每个 this.ctx原型(prototype)方法是 undefined 。尽管我更详细地搜索了有关原型(prototype)的解释,但我找不到我对 this 范围的误解。 .

最佳答案

您所在的事件处理程序中的 this 并不引用 Blackboard。在对 on 的调用中使用 .bind

this.end = this.end.bind(this);
this.canvas.on('mouseup', this.end);

关于javascript - 尝试访问原型(prototype)方法中的成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48644530/

相关文章:

javascript - 如何使用 v-for 迭代元素

javascript - 使 jsplumb 端点只读

javascript - JS 对象组合

javascript - 如何在对象内创建新对象时自动调用函数

javascript - 如何使用原型(prototype)创建原始包装对象

javascript - Angular JS - 数字过滤器 - 负数时更改颜色

javascript - 是否有新的 ES6+ 运算符的组合可以在对象数组中添加串联字段?

Javascript 正则表达式 - 多行

JavaScript 原型(prototype)编程

javascript - 如何传递原型(prototype)函数并在 JavaScript 中使用