JS Quiz: Hard: Prototype method and detached call

What is logged in strict mode?

"use strict";
class Counter {
  constructor() { this.n = 1; }
  inc() { this.n += 1; return this.n; }
}
const c = new Counter();
const fn = c.inc;
try {
  console.log(fn());
} catch (e) {
  console.log(e.name);
}
  • 2
  • NaN
  • TypeError
  • ReferenceError
0 voters

TypeError, because class methods are strict mode by default even without the pragma, and this never gets auto-boxed to globalThis like it would in a plain function.

Detach a regular old function from an object and call it bare, and non-strict mode quietly hands you the global object as this, so this. n += 1 just creates a garbage global property and moves on. Classes don’t get that safety net at all, strict or not, so the failure mode here isn’t really about the “use strict” string at the top.

JS Quiz answer: Option 3 (C).

Correct choice: TypeError

Why:
Detached method call has undefined this in strict mode, so accessing this.n throws.

Go deeper: