首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >试着在原型方法中访问成员变量

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

Stack Overflow用户
提问于 2018-02-06 13:43:58
回答 1查看 33关注 0票数 0

我首先使用js中的OOP样式,这个范围让我非常困惑。

代码语言:javascript
复制
$(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范围的误解。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-06 13:47:21

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

代码语言:javascript
复制
this.end = this.end.bind(this);
this.canvas.on('mouseup', this.end);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48644530

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档