0

There is a 'this' problem. I meant an instance by this, but it actually means <button> element. How can I add a value to the instance's array?

class MyClass {
  constructor() {
    this.arr = [];
  }

  addValue(event) {
    console.log(this); // 'this' is <button>add</button>
    this.arr.push('added'); // Error!
    console.log(this.arr);
  }
}

const c = new MyClass();
const btn = document.querySelector('button');
btn.addEventListener('click', c.addValue);
<button>add</button>
Miu
  • 846
  • 8
  • 22
  • 1
    btn.addEventListener('click', (event) => c.addValue(event)); – Dimava Nov 14 '22 at 21:47
  • 1
    Or `btn.addEventListener('click', c.addValue.bind(c));` (which avoids creating a closure with captures - and you can `removeEventListener` too - whereas with inline `=>`-style callbacks you can't un-register listeners. – Dai Nov 14 '22 at 21:48
  • Or use `addValue = (event) => {`…`}` in the field definition. See [How does the "this" keyword work, and when should it be used?](/q/3127429/4642212). – Sebastian Simon Nov 14 '22 at 21:49

0 Answers0