我是javascript的新手,我正在尝试使用HTML 5画布,我试图将文本框打印到屏幕上,但我似乎无法弄清楚我的问题是什么。我在chrome javascript控制台中遇到的错误是"未捕获的类型错误:无法读取未定义的属性'drawBox'
var Box = Box || function(x, y, title, desc){
Box.commonMethod.setup(x, y, title, desc);
};
function init(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "Black";
ctx.fillRect(0,0,150,75);
var b = new Box(10,10,'hello', 'this is text');
b.commonMethod.drawBox(ctx);
}
Box.commonMethod = {
locx: 25,
locy: 25,
desc: "",
title: "",
width: 100,
height: 100,
setup: function(x, y, title, description){
this.locx = x;
this.locy = y;
this.title = title;
this.desc = description;
},
drawBox: function(ctx){
ctx.font = "15px Arial";
ctx.fillRect(this.x,this.y, this.width+2, this.height);
ctx.fillStyle = "White";
ctx.fillRect(this.x+1,this.y+1, this.width, this.height-2);
ctx.fillStyle = "black";
ctx.fillText(this.title, this.x, this.y+15);
ctx.fillText(this.desc, this.x, this.y+40);
}
}
对象实例(即 b
在您的情况下)不要选取附加到其构造函数的方法(即 Box
在您的情况下)。但是他们在构造函数的原型上选取方法。
为对象实例定义公共属性/方法的正确方法是将它们定义为构造函数原型的一部分:
Box.prototype.commonMethod = { ...
如果执行此更改,以下代码行将起作用:
b.commonMethod.drawBox(ctx);
但是,您还必须将构造函数调整为:
var Box = Box || function(x, y, title, desc){
this.commonMethod.setup(x, y, title, desc);
};