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

182
Visualizações
How event handler inside JavaScript class/function got called?

I'm quite new on JS and got stuck on this problem. So I have this constructor which I understand how its works EXCEPT for one thing. How does an event handler got called from inside of an object or function?

I thought event handler could only be placed on global scope directly, not inside a function/object or another block scopes.

class Counter {
    constructor(element, defaultValue) {
       this.element = element;
       this.value = defaultValue;

       this.valueDOM = element.querySelector('.value');
       this.valueDOM.textContent = this.value;

       this.increase = this.increase.bind(this);
       this.btnIncrease = element.querySelector('.increase');
       this.btnIncrease.addEventListener('click', this.increase);
    }
    increase() {
       this.value++;
       this.valueDOM.textContent = this.value;
    }
}

const counterOne = new Counter(document.querySelector('.counter-one'), 0);
const counterTwo = new Counter(document.querySelector('.counter-two'), 0);

The HTML is quite simple, just a plain old counter like this.

<div class="container counter-one">
    <span class="value">0</span>
    <button class="increase">+</button>
</div>
<div class="container counter-two">
    <span class="value">0</span>
    <button class="increase">+</button>
</div>
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

addEventListener in this case is pointing directly at the local object's this.increase method. It is not pointing at the object's prototype function, but an actual distinct copy of that function which is attached to the object instance. Does that help?

about 4 years ago · Santiago Gelvez 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