On this page
  1. Functions, Closures & this
  2. Contents
  3. Lexical Scope & Closures
  4. The Four this Binding Rules
  5. Arrow Functions vs. Regular Functions

Functions, Closures & this

Prev: Core Syntax & Types | Up: tutorials | Next: Prototype Chain & new Instantiation Flow
Rel: Prototype Chain & new Instantiation Flow, Events & Delegation
Ref: MDN Web Docs — Closures
Tags: #public #web #javascript #tutorials #functions


Contents


Lexical Scope & Closures

A closure is a function paired with its lexical environment, retaining live access to outer variables after the enclosing function returns:

function makeCounter(start = 0) {
  let count = start;
  return (step = 1) => (count += step);
}

const next = makeCounter(10);
console.log(next(), next(5)); // 11 16

The Four this Binding Rules

For regular (non-arrow) functions, this is determined at call time, in descending precedence:

  1. new binding: new Foo() binds this to the newly created object.
  2. Explicit binding: fn.call(ctx, a, b), fn.apply(ctx, [a, b]), or fn.bind(ctx).
  3. Implicit (method) binding: obj.method() binds this to obj (detached const m = obj.method; m() loses obj).
  4. Default binding: undefined in strict mode / ES Modules, or globalThis in sloppy mode.

Arrow Functions vs. Regular Functions

Arrow functions ((x) => x * 2) have no own this, arguments, or [[Construct]] — they capture this lexically from their enclosing scope, making them ideal for callbacks and event listeners inside methods.

Linked from

Related notes