🟑 MediumFix the CodeπŸ› Debug Challenge

this lost in event listener

Buggy Code β€” Can you spot the issue?

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();
  }
}

Fixed Code

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 Explained

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

More Fix the Code Debug Challenges

🟒 EasyDeep clone breaks with JSON.stringifyβ†’πŸŸ‘ MediumObject mutation in array mapβ†’πŸ”΄ HardPrototype pollution vulnerabilityβ†’πŸŸ‘ MediumProxy trap modifies original object directlyβ†’

Practice spotting bugs live β†’

38 debug challenges with AI hints

πŸ› Try Debug Lab