Bind callback lihandler listener to a class
js
JavaScript
class Perso {
#element;
#name;
#onClick(event) {
let currentElement = event.target;
let persoInstance = this; // the Perso instance
console.log(currentElement, persoInstance);
}
constructor(name, color) {
this.#name = name;
this.#element = document.createElement("div");
this.#element.style.width = "40px";
this.#element.style.height = "40px";
this.#element.style.backgroundColor = color;
this.#element.title = name;
document.body.appendChild(this.#element);
this.#element.addEventListener('click', this.#onClick.bind(this));
}
get name() {
return this.#name;
}
}
const toto = new Perso("Toto", "blue");
const titi = new Perso("Titi", "red");