尝试在原型方法中访问成员变量

时间:2018-02-06 13:43:58

标签: 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")是画布元素。

正如我在评论中提到的,原型方法中的每个this.ctx都是undefined。虽然我搜索了关于原型更详细的解释,但我无法找到我对this范围的误解。

1 个答案:

答案 0 :(得分:1)

您所处的事件处理程序this未引用Blackboard。在通话.bind中使用on

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