CodeZettaInterview Hub

JavaScript · this · Mid-Level · Code Output

What is logged in strict mode? ```js const obj = { x: 10, getX() { return this.x; }, }; const g = obj.getX; console.log(obj.getX()); console.log(g()); ```

Short Interview Answer

`10` then a TypeError (or `undefined` access failure) because `g()` has default `this` of `undefined`.

Detailed Explanation

`obj.getX()` uses implicit binding, so `this` is `obj` and returns `10`. Assigning `const g = obj.getX` passes the bare function; calling `g()` uses default binding. In strict mode (and ES modules), `this` is `undefined`, so `this.x` throws TypeError. Fixes: `g.call(obj)`, `obj.getX.bind(obj)`, or wrap `() => obj.getX()`. This demonstrates why passing methods as callbacks often breaks.

Example

'use strict';
const obj = {
  x: 10,
  getX() { return this.x; },
};
const g = obj.getX;
console.log(obj.getX()); // 10
console.log(g()); // TypeError

Interview Tip

Ask whether the environment is strict/module — shows precision.

Common Mistake

Assuming `g` somehow still remembers `obj`.

Did you know this answer?