JSJavaScript
AdvancedLesson 13 of 16

Closures, Scope & this – JavaScript

Why functions "take along" their environment and what this really means.

A closure arises when a function accesses variables of its outer function and keeps using them even after the outer function has finished. This is how you create private state without classes:

function erzeugeZaehler() {
  let n = 0;
  return () => ++n;
}
const a = erzeugeZaehler();
const b = erzeugeZaehler();
console.log(a(), a(), b());   // 1 2 1

function memoize(fn) {
  const cache = new Map();
  return (x) => {
    if (!cache.has(x)) cache.set(x, fn(x));
    return cache.get(x);
  };
}
let aufrufe = 0;
const langsam = memoize((x) => { aufrufe++; return x * x; });
console.log(langsam(4), langsam(4), aufrufe);   // 16 16 1

A classic: var is function-scoped, let is fresh for each loop iteration. That is why with var all closures share the same variable.

var fns = [];
for (var i = 0; i < 3; i++) fns.push(() => i);
console.log(fns.map(f => f()));   // [3, 3, 3]

const fns2 = [];
for (let j = 0; j < 3; j++) fns2.push(() => j);
console.log(fns2.map(f => f()));  // [0, 1, 2]

this depends on *how* a function is called – not on where it is defined. Exception: arrow functions have no this of their own; they take it from their surroundings. If you pull a method out of its object, the binding is lost:

class Zaehler {
  n = 0;
  inc() { this.n++; return this.n; }
  incPfeil = () => { this.n++; return this.n; };
}
const z = new Zaehler();
const lose = z.inc;
try {
  lose();
} catch (e) {
  console.log(e.name);          // TypeError (this is undefined)
}
const gebunden = z.inc.bind(z);
console.log(gebunden(), z.incPfeil.call(null));   // 1 2

With call, apply and bind you set this explicitly:

function vorstellen(gruss) {
  return gruss + ", I am " + this.name;
}
console.log(vorstellen.call({ name: "Ada" }, "Hello"));
console.log(vorstellen.apply({ name: "Bob" }, ["Hi"]));
TipRule of thumb: in callbacks and class fields use arrow functions, for object methods use the shorthand method() { ... }. When this is "undefined", you have almost always called a method without its object.