I'm trying to create a class of dice set exactly like D&D, so that on a button press I can roll a die and log it to the console. I thought this would be a pretty simple thing but there is something I'm definitely missing. Here is what I have so far.
class Dice {
constructor (sides) {
this.sides = sides;
}
roll () {
console.log(Math.floor(Math.random() * this.sides) + 1);
}}
const d4 = new Dice (4);
const d6 = new Dice (6);
const d8 = new Dice (8);
const d10 = new Dice (10);
const d12 = new Dice (12);
const d20 = new Dice (20);
const d100 = new Dice (100);
const btn = document.getElementById('button');
btn.onclick = d20.roll;
I currently get "NaN", and I think I'm understanding it that 'this' is referring to the button press, not the d20 object, and therefore the 'sides' property is undefined, giving me back an undefined answer. I thought perhaps I had to bind 'this' to the class doing something like
btn.onclick = d20.roll.bind(this);
but I still get NaN... I'm not sure what's going on at this point.
Wow, after an hour of trying to figure out I solved my own question... I simply changed the roll method to an arrow function.
roll = () => {
console.log(Math.floor(Math.random() * this.sides) + 1);
}
Now I get the expected result without the need to bind the button. Who knew...