You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript报错:TypeError: layer.update is not a function 求助

解决无限滚动背景的TypeError: layer.update is not a function错误

错误原因及修复步骤

  • 核心问题:未正确引用实例属性
    在Background类的构造函数中,你通过this.layer1创建了Layer实例,但在赋值给this.backgroundLayers时写成了[layer1]——这里的layer1是未定义的全局变量,导致数组中存储的不是Layer实例,调用update方法自然会报错。
    修复:将该行改为this.backgroundLayers = [this.layer1];

  • Layer类的属性赋值错误
    在Layer的构造函数里,你错误地把speedModifier赋值给了this.height,覆盖了传入的高度参数,同时导致this.speedModifier未定义,会影响滚动速度计算。
    修复:将this.height = speedModifier;改为this.speedModifier = speedModifier;

  • 缺失game参数的潜在问题
    创建Background实例时const b = new Background();未传入game参数,而Layer的update方法依赖this.game.speed,会导致计算时出现NaN。
    修复:传入包含speed属性的game对象,示例:

const game = { speed: 2 };
const b = new Background(game);

修复后的完整代码

class Layer {
  constructor(game, width, height, speedModifier, image) {
    this.game = game;
    this.width = width;
    this.height = height;
    this.speedModifier = speedModifier;
    this.image = image;
    this.x = 0;
    this.y = 0;
  }
  update() {
    if (this.x < -this.width) this.x = 0;
    else this.x -= this.game.speed * this.speedModifier;
  }
  draw(context) {
    context.drawImage(this.image, this.x, this.y, this.width, this.height);
  }
}

export class Background {
  constructor(game) {
    this.game = game;
    this.width = 1667;
    this.height = 500;
    this.layer5image = document.getElementById("layer5");
    this.layer1 = new Layer(
      this.game,
      this.width,
      this.height,
      1,
      this.layer5image
    );
    console.log(this.layer5image);
    this.backgroundLayers = [this.layer1];
  }
  update() {
    this.backgroundLayers.forEach(function (layer) {
      layer.update();
    });
  }
  draw(context) {
    this.backgroundLayers.forEach((layer) => {
      layer.draw(context);
    });
  }
}

const game = { speed: 2 };
const b = new Background(game);
b.update();

内容的提问来源于stack exchange,提问作者Luka Talevski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 01:59:55