class Modal {
constructor(name) {
this.name = name;
document.getElementById('close')
.addEventListener('click', this.close);
}
close() {
console.log(`Closing ${this.name}`); // this.name is undefined!
this.remove();
}
}class Modal {
constructor(name) {
this.name = name;
// Fix 1: bind in constructor
document.getElementById('close')
.addEventListener('click', this.close.bind(this));
}
close() {
console.log(`Closing ${this.name}`); // works β
this.remove();
}
}
// Fix 2: Arrow function class field (auto-binds)
class Modal {
constructor(name) { this.name = name; }
close = () => { // arrow class field
console.log(`Closing ${this.name}`); // always correct this β
}
}Bug: addEventListener calls close as a plain function, losing the Modal instance as this. this becomes the button element (or undefined in strict mode).
Explanation: .bind(this) creates a new function with this permanently set. Arrow class fields (close = () => {}) are auto-bound to the instance and are the modern preferred approach.
Key Insight: Event listener callbacks lose this. Fix: .bind(this) in constructor, or arrow function class fields (the modern way).