How to Fix JavaScript 'this' Context Lost
In this tutorial, you'll learn about How to Fix JavaScript 'this' Context Lost. We cover key concepts, practical examples, and best practices.
The Problem
JavaScript loses the this context when a method is passed as a callback or extracted from its object, causing this to become undefined in strict mode or the global object in non-strict mode.
Quick Fix
Step 1: Use an arrow function
Arrow functions inherit this from the enclosing scope:
const user = {
name: 'Alice',
greet: function() {
console.log('Hello, ' + this.name);
}
};
setTimeout(user.greet, 100);
Hello, undefined
Wrap the call in an arrow function:
const user = {
name: 'Alice',
greet: function() {
console.log('Hello, ' + this.name);
}
};
setTimeout(() => user.greet(), 100);
Hello, Alice
Step 2: Use .bind()
Explicitly bind the context:
const user = {
name: 'Alice',
greet: function() {
console.log('Hello, ' + this.name);
}
};
setTimeout(user.greet.bind(user), 100);
Hello, Alice
Step 3: Use a class property arrow function
In class components, define methods as arrow functions:
class User {
constructor(name) {
this.name = name;
}
greet = () => {
console.log('Hello, ' + this.name);
}
}
const user = new User('Alice');
setTimeout(user.greet, 100);
Hello, Alice
Step 4: Store this in a variable
For older JavaScript, capture this in a variable:
const user = {
name: 'Alice',
greet: function() {
const self = this;
setTimeout(function() {
console.log('Hello, ' + self.name);
}, 100);
}
};
user.greet();
Hello, Alice
Prevention
- Prefer arrow functions for callbacks and event handlers.
- Use
.bind()when passing object methods as callbacks. - Define React class component methods as arrow functions.
- Avoid extracting methods from objects without binding them.
Common Mistakes with this context
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro