Course contentsShow
← JavaScript
Lesson 588 of 2,72314. The 'this' KeywordFree lesson

The 'var self = this' Pattern

When and why developers capture 'this' in a variable, and how arrow functions now solve this better.

The 'var self = this' Pattern

You'll learn: How developers used to capture this in a variable to avoid losing context, and why arrow functions are now the preferred solution.


Before arrow functions became standard, JavaScript developers faced a persistent problem: nested functions would lose access to the outer this. The workaround was to capture this in a regular variable before entering the nested scope.

The Classic Pattern

function Timer(duration) {
  this.seconds = duration;
  var self = this;  // Capture 'this' in a lexical variable
  
  setInterval(function() {
    self.seconds--;  // Use 'self' instead of 'this'
    console.log(self.seconds);
  }, 1000);
}

const timer = new Timer(5);

Here, var self = this creates a normal variable that follows lexical scope rules. The callback inside setInterval can't access the outer this (it would be undefined in strict mode or global otherwise), but it can access self through closure.

You might also see var that = this, var _this = this, or var me = this — they all do the same thing.

Why This Was Necessary

Regular functions determine their this at call-time. When setInterval calls your callback, it doesn't know about your outer object context. The self variable, however, is just a normal variable captured by the closure, so it survives perfectly.

The Modern Solution

function Timer(duration) {
  this.seconds = duration;
  
  setInterval(() => {
    this.seconds--;  // Arrow function uses outer 'this' automatically
    console.log(this.seconds);
  }, 1000);
}

Arrow functions use lexical this, meaning they inherit this from their surrounding scope. This eliminates the need for the self pattern entirely.

Key Takeaway: The var self = this pattern was a pre-arrow-function workaround that captured this in a closure variable. Modern code should use arrow functions instead, which naturally preserve the outer this value.