CS Fundamentals Trainer · Guides
Closures and `this` in JavaScript: scope, binding rules and the classic traps
How lexical scope and closures keep variables alive, the loop-with-var trap, and the four rules that decide what `this` is (new, explicit, method call, default), why arrow functions ignore them, and how to lose and recover `this` - with every output produced by running the code in Node.
4 min read
Two ideas cause a large share of JavaScript bugs: which variables a function can see (scope and closures) and what this means inside it. They look unrelated, but they share one root: where a function was written decides what it can see, and how it is called decides what this is.
Lexical scope and closures
A function can read the variables of the blocks and functions it was written inside, not the ones of whoever calls it. That is lexical scope. A closure is a function together with the variables it captured. The variables stay alive for as long as the function can still be called.
function counter() {
let n = 0;
return () => ++n;
}
const a = counter(), b = counter();
console.log(a(), a(), b());
This prints 1 2 1. Each call to counter creates a new n; a and b each hold their own. Closures are how you get private state, partial application and callbacks that remember context.
The loop trap
var is function-scoped: one variable shared by every iteration. let creates a fresh binding per iteration.
const fs = [];
for (var i = 0; i < 3; i++) fs.push(() => i);
console.log(fs.map(f => f())); // [ 3, 3, 3 ]
const gs = [];
for (let j = 0; j < 3; j++) gs.push(() => j);
console.log(gs.map(g => g())); // [ 0, 1, 2 ]
All three var closures read the same i, which is 3 when the loop ends. Prefer let and const; they also have a temporal dead zone, so reading one before its declaration throws a ReferenceError instead of giving undefined.
Closures and memory
A closure keeps the variables it uses reachable. A long-lived callback (an event listener you never remove, a cache keyed by closure) that captures a large object keeps that object alive. Remove listeners, and capture only what you need.
What this is
For an ordinary function this is decided at the call, by the first rule that applies:
new f():thisis the new object.- Explicit:
f.call(obj),f.apply(obj)or a function made byf.bind(obj):thisisobj. - Method call:
obj.f():thisisobj, the thing before the dot. - Plain call
f():thisisundefinedin strict mode (modules and classes are always strict) and the global object otherwise.
'use strict';
const user = {
name: 'Ana',
hi() { return this && this.name; },
};
console.log(user.hi()); // Ana
const detached = user.hi;
console.log(detached()); // undefined (plain call: no object before the dot)
const bound = user.hi.bind(user);
console.log(bound()); // Ana
The surprise is the second line: copying a method into a variable, or passing it as a callback (button.addEventListener('click', user.hi)), removes the object before the dot, so rule 3 no longer applies.
Arrow functions have no this of their own
An arrow function takes this from the scope where it was written, like any other captured variable, and ignores the four rules. That is exactly what you want for a callback inside a method:
const timer = {
name: 'T',
start() { return [1].map(() => this.name); },
};
console.log(timer.start()); // [ 'T' ]
It is exactly what you do not want for an object method or a prototype method, where you need the caller's this: const o = { f: () => this } gives you the outer this, not o.
Classes
Methods in a class are not bound to their instance. Passing instance.method as a callback loses this the same way. Fixes: bind in the constructor, use a class field with an arrow function (handle = () => { … }, one function per instance), or wrap at the call site (() => instance.method()).
Quick diagnosis
- "
thisis undefined" or "cannot read property of undefined" inside a callback: the method was detached. Bind it or wrap it. - "
thisis the window/global": a sloppy-mode plain call. Use modules or'use strict'. - "Arrow function method sees the wrong
this": use method syntax instead. - Event handlers added with
addEventListenergetthisset to the element for ordinary functions, but not for arrows.
Sources
- MDN: Closures.
- MDN: this.
- ECMAScript specification: Function Environment Records — where
thisbinding is defined.
Practise this topic: JavaScript