Skip to content
Advertisement

How to reconcile ‘this’ referencing DOM element and ‘this’ referencing class?

I’m having an issue understanding how I might go about using the this keyword to refer to a DOM element that is has been clicked, but also using that inside a class where this usually refers to the instance of that class.

Here’s a snippet of the relevant code:

class Passwords {
  constructor() {
    $('.password-column button.steel-button').on('click', this.selectButton);
  }
  
  selectButton() {
    $(this).toggleClass('selected');
    this.columnController();
  }
  
  columnController(){
    // A function that does something else
  }
}

The issue I’m having is that it doesn’t recognize columnController() as a function. I imagine this is because of the scope and how it works with ‘this’, but I’m not sure how to proceed.

In the above code, selectButton() is successfully applied to all the buttons specified, but the error is given on this.columnController(). Exact console error is:

Uncaught TypeError: this.columnController is not a function

Thank you in advance.

Advertisement

Answer

You can’t use this to represent both objects, so pick one and get the other one through some other mechanism.

For example: Use an arrow function to bind the this value to the class, then get the element from the event object.

class Passwords {
  constructor() {
    $('.password-column button.steel-button').on('click', this.selectButton);
  }

  selectButton = (event) => {
    $(event.currentTarget).toggleClass('selected');
    this.columnController();
  }

  columnController() {
    console.log("this runs");
  }
}

new Passwords();
.selected {
  background: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div class="password-column">
  <button class="steel-button">click</button>
</div>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement