skip to Main Content

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


  1. In your Background‘s constructor, you use initialize this.layer1 as a layer, then use layer1, without this, making it undefined, therefore, it can not find update.

    Here is the correct code:

    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]; // `layer1` is a property of `this`
    }
    
    Login or Signup to reply.
  2. Personally i don’t use class in JS. Instead of using class i use Constructer Functions

    Here’s an Example

    function Background(game, width) {
        this.game = game
        this.width = width
        this.update = function() {
            // Your Code Here
            console.log("It's A Update Function");
        }
    }
    
    // Don't forget to add new keyword
    const background = new Background("Kat Game", 100)
    
    // Call
    console.log("Game : ", background.game)
    background.update()
    
    // Output
    // Game : Kat Game
    // It's A Update Function
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search