Javascript 尝试在prototype方法中访问成员变量

Javascript 尝试在prototype方法中访问成员变量,javascript,prototype,Javascript,Prototype,我是第一个在js中使用OOP风格的人,这个范围让我很困惑 $(文档).ready(函数(){ $(“#cv”).attr({ 宽度:“860px”, 高度:'645px' }); var ctx=新黑板($(“#cv”); }); 功能黑板(画布){ this.canvas=画布; this.ctx=this.canvas.get(0.getContext(“2d”); 此图为假; this.canvas.on('mousedown',this.press); this.canvas.on('m

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

$(文档).ready(函数(){
$(“#cv”).attr({
宽度:“860px”,
高度:'645px'
});
var ctx=新黑板($(“#cv”);
});
功能黑板(画布){
this.canvas=画布;
this.ctx=this.canvas.get(0.getContext(“2d”);
此图为假;
this.canvas.on('mousedown',this.press);
this.canvas.on('mousemove',this.move);
this.canvas.on('mouseup',this.end);
this.setShape();
}
Blackboard.prototype.setShape=函数(颜色、宽度){
this.color='白色';
这个宽度=1;
如果(颜色!=null){
这个颜色=颜色;
}
如果(宽度!=null){
这个。宽度=宽度;
}
this.ctx.strokeStyle=this.color;
this.ctx.lineWidth=this.width;
}
Blackboard.prototype.press=函数(事件){
console.log(this.ctx);//未定义!
this.ctx.beginPath();
this.ctx.moveTo(event.pageX,event.pageY);
此图为真;
}
Blackboard.prototype.move=函数(事件){
如果(本图纸){
this.ctx.lineTo(event.pageX,event.pageY);
这个.ctx.stroke();
}
}
Blackboard.prototype.end=函数(事件){
此图为假;
}
$(“#cv”)
是画布元素


正如我在评论中提到的,原型方法中的每个
this.ctx
都是
未定义的。虽然我搜索了关于原型的更多详细解释,但我找不到我对
这个
的范围有什么误解您所处的事件处理程序
这个
不涉及
黑板
。在对
上的
的调用中使用
.bind

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

我不确定用绑定实例覆盖原型中的
.end
方法是否是个好主意。我会将
this.end.bind(this)
传递给事件处理程序。@Alnitak这是一个好主意,否则您不能取消
。只是为了讨论,可以使用
名称空间的
事件来允许使用
。off
@gabykag.Petrioli这是真的。我已经看到了backbone.FWIW,对于一个可能不会在页面上出现多次的对象,我不会为基于原型的代码而烦恼。