![](/img/trans.png)
[英]I'm getting “Uncaught (in promise) TypeError: Cannot read property 'data' of undefined” error in axios patch api
[英]I'm getting the error Uncaught TypeError: Cannot read property 'drawBox' of undefined, Can anyone spot the issue?
我是javascript新手,正在尝试使用HTML 5画布,我正在尝试在屏幕上打印文本框,但似乎无法弄清问题所在。 我在Chrome浏览器javascript控制台中遇到的错误是“未捕获的TypeError:无法读取未定义的属性'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);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.