我有一个构造函数Chomp
,它创建了一个canvas元素;具有canvas元素的属性是this.c
,但是当我尝试在构造函数的方法中调用this.c
上的函数时,我收到错误:TypeError: Cannot read property 'beginPath' of undefined (line 28 in function Chomp.chomping)
。我需要知道为什么会这样,以及如何解决这个问题。以下是我的代码对此问题很重要的部分。
更新:这是第二次通过animate函数this.c
变为未定义,因此,我的错误必须位于方法Chomp.prototype.animate
中。
var Chomp = function(x, y) {
/*many properties*/
this.element = document.createElement("canvas");
this.c = this.element.getContext("2d");
/*a few more properties*/
}
Chomp.prototype.chomping = function() {
/*some conditions,... properties like this.width were defined in Chomp,
but omitted because of their lack of importance to the question.*/
this.c.clearRect(/*arguments*/);
this.c.beginPath();
this.c.moveTo(/*arguments*/);
this.c.arc(/*arguments*/);
this.c.lineTo(/*arguments*/);
this.c.lineTo(/*arguments*/);
this.c.fillStyle = "yellow";
this.c.fill();
/*more conditions*/
}
Chomp.prototype.animate = function() {
Chomp.prototype.chomping.apply(this);
setTimeout(function(){
Chomp.prototype.animate.apply(this);
}, 50);
}
var yellow = new Chomp(30, 60);
Chomp.prototype.animate.apply(yellow);
答案 0 :(得分:0)
Chomp.prototype.animate = function() {
Chomp.prototype.chomping.apply(this);
setTimeout(function(){
Chomp.prototype.animate.apply(this);
}, 50);
}
setTimeout认为这是指窗口对象或全局对象,所以我需要定义一个新变量,比如that
并将其设置为this
,以便我函数中的参数在setTimeout中是that
,如下所示:
Chomp.prototype.animate = function() {
Chomp.prototype.chomping.apply(this);
var that = this;
setTimeout(function(){;
Chomp.prototype.animate.apply(that);
}, 50);
}