I’m new to JavaScript so I was taking a YouTube course to try and learn more. When I began making an infinite scrolling background, I got the error ‘TypeError: layer.update is not a function’ in the console
, this is the scroller code
class Layer {
constructor(game, width, height, speedModifier, image) {
this.game = game;
this.width = width;
this.height = height;
this.height = 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 = [layer1];
}
update() {
this.backgroundLayers.forEach(function (layer) {
layer.update();
});
}
draw(context) {
this.backgroundLayers.forEach((layer) => {
layer.draw(context);
});
}
}
const b = new Background();
b.update();
I tried to ask ChatGPT and I thought that that would help, it did not, instead it told me to add arrow syntax, which I already did. After that I looked at microsoft IntelliSense(or whatever it’s called) and changed it to an anonymous function(or something like that), I honestly didn’t expect anything and nothing happened
2
Answers
In your
Background
‘s constructor, you use initializethis.layer1
as a layer, then uselayer1
, withoutthis
, making it undefined, therefore, it can not findupdate
.Here is the correct code:
Personally i don’t use class in JS. Instead of using class i use Constructer Functions
Here’s an Example