0

Here's the thing. I looked up a pong game for java and now I want to try to make it in js. I'm still not good at js and I'm trying to code a simple pong game while trying to use classes like in java. But the problem is I always get this error "Uncaught TypeError: Cannot read properties of undefined (reading 'move')". I've tried looking online for solutions but I still don't get it. This also shows up for the other two methods, draw and run. Can anyone please kindly tell me why this happens?

class Game {
    constructor() {
        this.run();
    }
    run() {
        this.move();
        this.draw(ctx);
        requestAnimationFrame(this.run);
    }
    draw(ctx) {
        paddle.draw(ctx);
    }
    move() {
        paddle.move();
    }
}

let game = new Game();

Thank you very much in advance to anyone who will answer this.

Arby
  • 1
  • 3

1 Answers1

0

In this case, you call to the method of instancepaddle and it's not declare yet. That's why, javascript cheat as paddle undefine variable.

  • That would throw the error "paddle is not defined", not "Cannot read properties of undefined (reading 'move')" – Ivar May 17 '22 at 10:20
  • @Ivar Inside the `move` function you call `move()` method of `paddle`, but `paddle` was not define yet. That's why javascript throw error: "Cannot read properties of undefined" ```javascript move() { paddle.move(); } ``` – Hoàng Anh May 17 '22 at 10:41
  • Yeah I kind of forgot about saying that the paddle object is a global variable. Thank you very much though for your time. – Arby May 17 '22 at 10:43
  • @HoàngAnh No, it isn't. If `paddle` wasn't at all defined, it would throw the error "paddle is not defined". This error is thrown because `this` is undefined in the `requestAnimationFrame(this.run)` callback. (It is trying to read `.move()` from an undefined value (`this`).) – Ivar May 17 '22 at 10:46
  • @Ivar Oh, i saw it :v In `constructor` function, `this` instance is not define yet. That's why you can't call its method, right? :v – Hoàng Anh May 18 '22 at 03:17
  • @HoàngAnh `this` is a special keyword which you can't define yourself. See [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work). To why it doesn't work in this case, see the question linked at the top of this question (under "_This question already has answers here_"). – Ivar May 18 '22 at 06:58