this in Classes & Method Binding

Master the most confusing keyword in JavaScript. Learn why 'this' gets lost in callbacks and how to lock it down using Arrow Functions.

JavaScript8 min readConcept 25 of 62

The fragile 'this' keyword

In JavaScript classes, the this keyword refers to the current instance of the object. For example, this.name gets the name of the specific object executing the method.

However, this is not locked in place. Its value is determined entirely by **how the method is called**, not where it was defined.

Losing Context in Callbacks

If you call a method directly like player.attack(), this works perfectly and points to player.

But if you pass that method as a callback to an event listener or a timeout (e.g., setTimeout(player.attack, 1000)), it gets separated from the object! When the timer finally runs the function, it calls it nakedly as attack(). Because classes run in strict mode, this instantly becomes undefined.

The Modern Fix: Arrow Functions

Historically, developers fixed this by manually binding the method in the constructor using .bind(this). This forced the method to permanently remember its context.

Today, the modern solution is to use **Class Fields with Arrow Functions**. If you define a method as attack = () => { console.log(this.name) }, the arrow function automatically locks this to the instance at the moment of creation. It can never be lost!

The Binding Sandbox

Compare a standard class method against an arrow function field to see exactly when and why 'this' gets ripped away.

The Binding Sandbox

class Player {
name = "Link";
// 1. Standard Method (Lives on Prototype)
standardAttack() {
return this.name;
}
// 2. Arrow Field (Lives on Instance)
arrowAttack = () => {
return this.name;
}
}
const player = new Player();
Execute:
Select an execution scenario above to see how this behaves.
iWhen dealing with React event handlers like onClick={this.handleClick}, defining the method as an arrow function completely prevents the context crash.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Why does `setTimeout(player.attack, 1000)` cause `this` to become undefined?
  2. 2How does an Arrow Function fix the 'this' problem?
  3. 3Which approach uses less memory if you instantiate 10,000 objects?

Remember this

  • In JavaScript, the value of this is determined by HOW a function is called, not where it is defined.
  • Passing a standard class method as a callback strips away its object context, making this undefined.
  • Arrow Functions lexically bind this, meaning it permanently locks onto the surrounding instance.
  • Using class fields with arrow functions (myFunc = () => {}) is the modern fix for lost context.
  • Arrow functions cost slightly more memory because they exist on the instance, not the Prototype.

Done with this concept?

Mark it complete to track your progress. No login needed.