1

I am trying to write some code in plain javascript using classes. I can do this easily in React and JQuery and without classes, but I am really struggling to understand the issue I am having in plain javascript classes.

Here is my code:

class Game {
  constructor() {
    this.balls = []
    for (let i = 1; i <= 80; i++) {
      this.balls.push(i)
    }
  }
  getBall() {
    // https://stackoverflow.com/a/4960020/3482632
    const ball = Math.floor(Math.random() * 80) + 1
    this.balls = this.balls.filter(n => n !== ball)
    return ball
  }
  drawBall(e) {
    const ball = this.getBall()
    console.log("ball drawn: " + ball)
  }
}

let g = new Game()
g.drawBall()
//const drawBallButton = document.getElementById("draw_ball")
//drawBallButton.onclick = g.drawBall

The code as written works fine, but I want the drawBall to fire on the button click. If I comment out the g.drawBall code and uncomment the last two lines, drawBall fires just fine, but then I get the following error:

uncaught TypeError: this.getBall is not a function at HTMLButtonElement.drawBall

I have tried to put the click handler inside the constructor but it makes no difference. What am I doing wrong?

TIA

FZs
  • 16,581
  • 13
  • 41
  • 50
grayson
  • 945
  • 1
  • 11
  • 28

1 Answers1

3

You are calling drawBall as a regular function, so it's missing this context.

Try this:

const drawBallButton = document.getElementById("draw_ball");
drawBallButton.onclick = () => g.drawBall();
Guerric P
  • 30,447
  • 6
  • 48
  • 86
  • To add up some more information on *this* in javascript: https://medium.com/better-programming/understanding-the-this-keyword-in-javascript-cb76d4c7c5e8 – Monsieur Merso Feb 08 '21 at 12:20
  • I dint know why this question was edited as the supposed previously answered question was no help, But @Guerric-p answer is spot and exactly what I needed. – grayson Feb 08 '21 at 12:36