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

189
Vistas
Why my function i event listener can't be called again after initial calling?

I have the following code:

HTML

 <button>Add Name</button>
 <ul id="names"></ul>

JS

class NameField {
    constructor(name) {
        const field = document.createElement('li');
        field.textContent = name;
        const nameListHook = document.querySelector('#names');
        nameListHook.appendChild(field);
    }
}

class NameGenerator {
    constructor() {
        const btn = document.querySelector('button');
        btn.addEventListener('click', this.addName);
    }

    addName() {
        const name = new NameField("Max");
    }
}

const gen = new NameGenerator();

so here when i click on the button, then every time the function addName gets executed and max is printed in the HTML.

But when i change the line to:

 btn.addEventListener('click', this.addName());

then i get initially printed Max on the browser HTML which is expected because i call the function immediately, i did not ommited the ().

But i don't understand why after the iniitial printing,when i click on the button i don't get printed Max again ? why is that ?

Okay i got initial printing on HTML, but should not i get printed now again Max when i click on the button ? And why am i not getting ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This is because you have to hand over a reference to a function.
If you write

 btn.addEventListener('click', this.addName());

javascript calls this.addName() instantly and executes the return value of this.addName() when you click the button.

But this.addName() has no explicit return value, so it returns the standard Javascript return value, which is undefined.

So essentially what your code does is

btn.addEventListener('click', undefined);

except that this undefined is returned from your call to this.addName() (which runs the function once, hence you see the console output).

about 4 years ago · Juan Pablo Isaza 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