2
class UI {
  constructor() {
    this.div = document.getElementById('div1');
  }

  doSomethingOnClick() {
     console.log(this.div.textContent);
  }
}

const ui = new UI();

document.getElementById('button1').addEventListener('click', ui.doSomethingOnClick);
// in this context, the this inside the doSomethingOnClick method refers to the element being clicked

ui.doSomethingOnClick();
// in this context, the this refers to the class

In this case, is there any straight forward way of accessing this.div inside the method, because I would like to access both the clicked element and the class properties inside that method ?

P.S. honestly, before writing this, I went through several big threads about classes and the this keyword, and couldn't find a solution for my particular use case.

  • There is really a ton of information about this in [How does the this keyword work?](https://stackoverflow.com/q/3127429/5459839) with more than one solution for your case, and explanation. – trincot Jul 28 '20 at 12:13

1 Answers1

1

You can use Function.bind to define the this used for the call

class UI {
  constructor() {
    this.div = document.getElementById('div1');
  }

  doSomethingOnClick() {
     console.log(this.div.textContent);
  }
}

const ui = new UI();

document.getElementById('button1')
  .addEventListener('click', ui.doSomethingOnClick.bind(ui));
<div id="div1">content</div>
<button id="button1">hi</button>

with access to the event as asked in the comment

class UI {
  constructor() {
    this.div = document.getElementById('div1');
  }

  // only need to add an argument here
  doSomethingOnClick(event) {
     console.log(event.target);
     console.log(this.div.textContent);
  }
}

const ui = new UI();

document.getElementById('button1')
  .addEventListener('click', ui.doSomethingOnClick.bind(ui) );
<div id="div1">content</div>
<button id="button1">hi</button>
jonatjano
  • 3,576
  • 1
  • 15
  • 20
  • How would you go about accessing the clicked button inside the method, since the this keyword now refers to the class ? – Aleksandar Ivanov Jul 28 '20 at 14:18
  • I'd do `.addEventListener('click', e => ui.doSomethingOnClick.bind(ui)(e) )` and add the clickEvent as a parameter for `doSomethingOnClick`, I added a second snippet to the answer, take a look – jonatjano Jul 28 '20 at 14:25
  • 1
    made some tests and my previous comment overcomplicate things, look at the second snippets, way easier – jonatjano Jul 28 '20 at 14:37