The 'self' Pattern
You'll learn a classic workaround for preserving this in nested functions before arrow functions existed.
The Problem It Solved
Before ES6 arrow functions, nested functions and callbacks would lose access to the outer this. Since each function created its own this context, developers needed a way to "carry" the outer this into inner scopes.
The Pattern
The solution was simple: store this in a regular variable before entering a nested function. By convention, this variable was often named self, that, or _this:
const user = {
name: 'Alice',
friends: ['Bob', 'Carol'],
greetFriends: function() {
const self = this; // Save 'this' to a variable
this.friends.forEach(function(friend) {
// 'this' here is undefined/global
// But 'self' still points to the user object
console.log(self.name + ' greets ' + friend);
});
}
};
user.greetFriends();
// Alice greets Bob
// Alice greets Carol
Why It Works
Variables follow normal lexical scoping rules. When you capture this in a variable like self, that variable is accessible in nested functions through closure. Unlike this, self doesn't change based on how a function is called—it's just a regular variable.
Modern Alternative
Today, arrow functions handle this automatically through lexical this, making the self pattern largely obsolete. However, you'll still see it in older codebases and legacy libraries.
Key Takeaway: The self pattern stores this in a variable to preserve access in nested functions—a workaround made obsolete by arrow functions but common in pre-ES6 code.