为什么我的代码认为 canvas 函数在 JavaScript 中的构造函数原型中是未定义的
Why does my code think that canvas functions are undefined in my constructor's prototype in JavaScript?
我有一个构造函数,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);
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);
}
相关文章:
- 如何从构造函数中调用js原型方法
- 通过原型/构造函数从复选框输出值
- Javascript:继承原型而不重新定义构造函数
- 使用sinon.js创建一个“;“间谍对象”;使用基于真实构造函数/原型的间谍方法
- 使用构造函数 - 原型从文本框输出值
- 在构造函数中定义函数会比将其附加到原型消耗更多的内存
- JS构造函数的原型属性与其原型之间的区别
- Javascript 中的构造函数不会返回由原型函数传递的正确值
- 构造函数原型-继承混淆
- 为什么我的代码认为 canvas 函数在 JavaScript 中的构造函数原型中是未定义的
- 我应该使用构造函数/原型吗?
- 对象文字与构造函数+原型
- 从画布构造函数原型中绘制图像
- 如何给构造函数/原型函数增加值?
- 构造函数.原型不在原型链中
- 向构造函数原型添加方法
- 为什么组合构造函数/原型模式返回对象类型
- 更改构造函数原型时出现问题
- 如何创建带有未分配属性的Javascript构造函数/原型
- 构造函数-原型- __proto__