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

185
Visualizações
Javascript class this.x is not a function when calling function from inside class

I have a button which, when pressed, should call a function which calls another function. this is inside a class.

class cat{
    constructor(){
        this.event_listener();
    }

    log_2(){
        console.log("cat 2");
    }
    log_1(){
        console.log("cat 1");
        this.log_2();
    }

    event_listener(){
        document.getElementById("cat_button").addEventListener("click", this.log_1);
    }
}

let cat1 = new cat();

The first function, this.log_1(), is called when the button is pressed and outputs "cat 1" as expected, but then the error

this.log_2 is not a function

appears on the console, although log_2() is defined within the class. How can I structure this so that log_2() is recognised as a function?

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

0

this is what called the function. In this instance an event called the function so this refers to the event.

What you'll want to do is bind the method before using is as a reference. Now this will refer to the instance of the class.

event_listener(){
  this.log_1 = this.log_1.bind(this)

  document.getElementById("cat_button").addEventListener("click", this.log_1);
}
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