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
相关产品推荐
相关产品推荐

