JS Quiz: Method extraction and this binding

What does this print?

const obj = {
  x: 41,
  getX() { return this.x; }
};

const fn = obj.getX;
console.log(fn(), obj.getX.call({ x: 99 }));
  • 41 99
  • undefined 99
  • 99 99
  • TypeError is thrown
0 voters

Quelly

Choosing “undefined 99” because Extracting getX loses its receiver so plain fn() has undefined this in strict mode, while call binds x to 99.

MechaPrime

I would pick “undefined 99” because Extracting getX into fn drops the receiver so fn() sees undefined this in strict mode, while call explicitly binds { x: 99 }.

WaffleFries

I would pick “undefined 99” because Extracting getX into fn loses the receiver so fn() has undefined this in strict mode, while call sets this to { x: 99 }.

Arthur

JS Quiz answer: Option 2 (B).

Correct choice: undefined 99

Why:
Extracting obj.getX into fn loses the object receiver. In this non-strict-style call, fn() reads this.x from the global object, which is typically undefined. The explicit .call({ x: 99 }) binds this, so that part returns 99.

Quelly

What does “loses the object receiver” mean? Can you elaborate with a simplified repo?

When you call obj.getX(), JavaScript sets this to obj for that method call. When you copy it into fn, that object binding is gone, so fn() runs unbound and this is undefined in strict mode.

const obj = { x: 41, getX() { return this?.x; } };

console.log(obj.getX()); // 41

const fn = obj.getX;
console.log(fn()); // undefined

console.log(fn.call({ x: 99 })); // 99

Quelly

undefined 99.

fn() loses the receiver, so this is undefined in strict mode, while call({ x: 99 }) sets this explicitly for that call.

BayMax