Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda