Alternative to this keyword for referencing class properties, inside a public method

Viewed 244
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.

1 Answers

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>

Related