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

120
Visualizações
Access property of an object from jquery function within the object (JavaScript/jQuery)

I have the following class:

class Traffic {
    constructor(name) {
        this.name = name;
    }
    setEventListeners() {
        $("#btn").on('click', function() {
            $(this).text(name);
        }
    }
}

When clicking on the <button id="btn"></button>This throws the error: name is undefined. This makes sense to me as I would normally use this.name to access the object's properties. However, because I am inside jQuery, now this refers to the jQuery object.

How can I access the name property of the Traffic object?

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

0

You can just declare a new variable outside the function where this still points to the class instance.

setEventListeners() {
    const name = this.name;
    $("#btn").on('click', function() {
        $(this).text(name);
    }
}
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