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