Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

281
Visualizações
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 recognise 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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda