Interview Q&A · JavaScript · 8 questions in this topic

`this` Binding Rules — JavaScript Interview Q&A

All JavaScript topics

The four (plus one) binding rules — implicit, explicit, new, default, and lexical. Part of Objects, Prototypes & this · 204 questions in the JavaScript bank.

How is `this` determined (the four binding rules)?

Answer

Call-site rules in precedence order: new (fresh object), explicit (call/apply/bind), implicit (owning object: o.f()), default (undefined in strict/modules, global in sloppy). Arrows skip all four — lexical from enclosing scope.

New > explicit > implicit > default, arrows opt out entirely.

Key points

  1. 1new — fresh instance.
  2. 2explicit — call/apply/bind argument.
  3. 3implicit — receiver object.
  4. 4default — undefined (strict) / global (sloppy).

Example

Example.jsjs
function f() { return this; }
f();              // undefined (strict) — default binding
({ m: f }).m();  // the object — implicit binding

💡 Recite in precedence order — interviewers grade the ordering.

Why does `this` get lost in callbacks (and how do you fix it)?

Answer

Passing obj.method detaches the function — the callback invokes it bare (default binding), losing the receiver. Fixes: arrow wrapper (() => obj.method()), bind at registration, or pass receiver where APIs accept it (forEach's thisArg).

Detachment-loses-receiver is the bug shape behind every lost-this.

Example

Example.jsjs
class UI {
  constructor() { this.n = 0; }
  attach(btn) {
    btn.addEventListener('click', () => this.tick()); // arrow keeps UI
  }
  tick() { this.n++; }
}

💡 Arrow-at-registration is the standard fix.

What does `new` actually do (four steps)?

Answer

Creates a fresh object linked to the constructor's prototype, calls the constructor with this bound to it, and returns this (unless the constructor returns its own object). new-less calls on constructors misbind this (strict: TypeError fast-fail).

Fresh-link-call-return is the four-step mantra.

Key points

  1. 1Create — fresh object, prototype linked.
  2. 2Bind — this is the new object.
  3. 3Return — this unless object returned.

Example

Example.jsjs
function P(n) { this.n = n; }
const p = new P(1); // p.__proto__ === P.prototype

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits