The below code will create instances of the ButtonToPress class and create a button in HTML. When one presses the button the expected behavior would be to log the class's variable n to the console, however I get "undefined" when I do this.
Maybe there is a better way to set this up? I would like to have the specific class instance tied to the specific button.
Javascript:
class ButtonToPress {
constructor(n) {
this.n = n;
const button = document.createElement('button');
button.onclick = this.print;
button.innerText = this.n
document.getElementById('container').appendChild(button);
}
print() {
console.log(this.n);
}
}
let buttons = [];
for (let i = 0; i < 10; i++) {
buttons[i] = new ButtonToPress(i);
}
HTML:
<!DOCTYPE html>
<html>
<body>
<div id="container">
</div>
<script src="temp.js"></script>
</body>
</html>