2

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>
Eric HB
  • 867
  • 6
  • 17

1 Answers1

4

Inside your constructor:

button.onclick = this.print.bind(this);

You need to bind functions when you pass them, if the function uses 'this' inside. Otherwise this becomes the window object.

[edit] as @Bergi points out in the comments, this is the button, not the window object. A jsfiddle to prove as much: https://jsfiddle.net/k3s4cmrv/

Another jsfiddle to show that you can access the Class instance by setting it on the button (don't know if this is advisable, but it is apparently possible): https://jsfiddle.net/r2uf6L5c/

TKoL
  • 13,158
  • 3
  • 39
  • 73