为什么我的代码认为 canvas 函数在 JavaScript 中的构造函数原型中是未定义的

Why does my code think that canvas functions are undefined in my constructor's prototype in JavaScript?

本文关键字:构造函数 原型 未定义 JavaScript 代码 我的 函数 canvas 为什么      更新时间:2023-09-26

我有一个构造函数,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);
}