Bugs

JavaScript `this` Context Bugs: Why They Happen and How to Fix Them

JavaScript's this is determined by how a function is called, not where it's defined. This causes bugs when methods are passed as callbacks or event handlers.


❌ Lost this in Event Handler

class Timer {
  constructor() { this.count = 0; }
  start() {
    setInterval(function() {
      this.count++;  // Bug: 'this' is undefined!
      console.log(this.count);
    }, 1000);
  }
}

✅ Fixed with Arrow Function

class Timer {
  constructor() { this.count = 0; }
  start() {
    setInterval(() => {  // Arrow function inherits 'this'
      this.count++;
      console.log(this.count);
    }, 1000);
  }
}
💡

Pro tip: Arrow functions don't have their own this — they inherit it from the enclosing scope. Use .bind(this) when you need a named function reference.

Paste this code into LearnCodeGuide

Detect JavaScript vulnerabilities and bugs automatically with AI-powered analysis.

Analyze JavaScript Code →

Related Guides

Javascript Closure BugsJavascript Async Await MistakesJavascript Hoisting Bugs