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 ?
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).