this Binding
in Classes
Master how JavaScript's this keyword behaves inside class methods: when it works, when it breaks, and how to fix it.
What is this?
this is a special keyword in JavaScript that refers to the current execution context: the object that is "owning" or calling the function at the moment it runs.
In classes, this usually refers to the instance of the class: the specific object you created with new.
A Quick Class Refresher
The Dot Rule of this
The Core Rule for Classes
When this Breaks
Visualizing the Detachment
Regular vs Arrow Functions
| Regular Method | Arrow Function | |
|---|---|---|
| Syntax | bark() { ... } |
bark = () => { ... } |
| this binding | Set at call time (dynamic) | Set at definition time (lexical) |
| Can be detached? | Breaks if detached | Safe when detached |
| Where it lives | On the prototype (shared) | On each instance (copied) |
| Memory | Efficient (one copy) | Less efficient (per instance) |
Three Ways to Fix this
Step-by-Step Checklist
Example 1: Arrow Field Fix
Example 2: The .bind() Fix
Example 3: Wrapper Arrow at Call Site
The this Decision Flowchart
Common Mistakes
Summary Table
| Call Pattern | this = | Safe? |
|---|---|---|
obj.method() |
obj | ✓ Yes |
const fn = obj.method; fn() |
undefined | ✕ No |
setTimeout(obj.method, 100) |
undefined | ✕ No |
method = () => { ... } (arrow) |
instance (captured) | ✓ Always |
this.method.bind(this) |
instance (locked) | ✓ Always |
() => obj.method() (wrapper) |
obj (dot preserved) | ✓ Always |
Question 1 of 5
class Counter {
constructor() { this.count = 0; }
increment() { this.count++; }
}
const c = new Counter();
const inc = c.increment;
inc();
What happens when inc() is called?
Question 2 of 5
Which fix allows a class method to keep its this context when passed as a callback?
Question 3 of 5
class Logger {
constructor(name) { this.name = name; }
log = () => { console.log(this.name); }
}
const a = new Logger("Alpha");
const b = new Logger("Beta");
setTimeout(a.log, 100);
What does setTimeout print after 100ms?
Question 4 of 5
What does .bind(this) in a constructor actually do?
Question 5 of 5
class App {
constructor() { this.data = [1, 2, 3]; }
process() {
return this.data.map(function(n) {
return n * this.data.length;
});
}
}
new App().process();
What happens when process() runs?