← Back to JavaScript, page 9

javascript-0169 · Medium mid

What does this refer to in these callback and class puzzles, and how do you fix each one?

this is set by how a function is called, not where it is written, except for arrow functions, which take this from the surrounding scope. A method passed as a callback loses its object, a timer or array callback gets undefined or the global object, bind fixes this permanently and cannot be changed by call, and arrow class fields bind this per instance. Constructors called without new fail in classes.

Full answer

The rule of thumb: for a regular function, this is decided at the call site. obj.method() sets this to obj. method() alone gives undefined in strict mode (and always in classes and modules) and the global object in sloppy mode. fn.call(x), fn.apply(x), and fn.bind(x) set it explicitly. new Fn() creates a new object as this. An arrow function has no this of its own and uses the one of the scope where it was defined.

Puzzles:

  1. A method extracted into a variable, or passed as a callback, loses its object. In a class, the call throws a TypeError when it reads a property of undefined.
  2. setTimeout(obj.method, 0) calls the function without the object. In browsers this is the window, and in Node.js it is the Timeout object. Neither is your object.
  3. Array method callbacks (forEach, map) receive this as undefined unless a second thisArg argument is given.
  4. An arrow function inside a method keeps the method's this, so it works for timers inside methods. An arrow function as an object literal method does not, because it takes this from the outer scope, not from the object.
  5. bind creates a function with a fixed this. Binding again, or calling it with call, cannot change it. new on a bound function ignores the bound this.
  6. A class field with an arrow function (handle = () => ...) creates one function per instance with this fixed to that instance, which survives being passed around. A normal method lives on the prototype and does not.
  7. In a subclass constructor, this cannot be used before super() is called, and calling a class without new throws.

Fixes: bind in the constructor or at the call site, wrap in an arrow function, use an arrow class field, or avoid this by closing over a variable. Name which one you choose and the trade-off: arrow fields cost memory per instance and cannot be overridden through super.

javascript
'use strict';
const attempt = (label, fn) => {
  try {
    console.log(label.padEnd(36), '->', fn());
  } catch (error) {
    console.log(label.padEnd(36), '->', error.name);
  }
};

class Counter {
  count = 0;
  constructor(label) { this.label = label; }
  inc() { return `${this.label}:${++this.count}`; }
  incArrow = () => `${this.label}:${++this.count}`;
}
const counter = new Counter('c1');

attempt('1. method called normally', () => counter.inc());
attempt('1b. method extracted', () => { const { inc } = counter; return inc(); });
attempt('1c. arrow field extracted', () => { const { incArrow } = counter; return incArrow(); });
attempt('1d. bound method extracted', () => { const bound = counter.inc.bind(counter); return bound(); });
attempt('1e. wrapped in an arrow', () => [1].map(() => counter.inc()));

attempt('2. array callback, no thisArg', () => [1].map(counter.inc));
attempt('2b. array callback with thisArg', () => [1].map(counter.inc, counter));

const obj = {
  name: 'obj',
  regular() { return this?.name; },
  arrow: () => (typeof this === 'object' ? Object.keys(this).length + ' keys on module.exports' : typeof this),
  later() { return [1].map(() => this.name); },
  laterRegular() { return [1].map(function () { return this?.name; }); },
};
attempt('4. regular method', () => obj.regular());
attempt('4b. arrow as object method', () => obj.arrow());
attempt('4c. arrow inside a method', () => obj.later());
attempt('4d. regular function inside a method', () => obj.laterRegular());

function whoAmI() { return this?.id; }
const a = { id: 'a' };
const b = { id: 'b' };
const boundToA = whoAmI.bind(a);
attempt('5. bind then call with b', () => boundToA.call(b));
attempt('5b. bind twice', () => whoAmI.bind(a).bind(b)());
attempt('5c. call', () => whoAmI.call(b));
attempt('5d. new on a bound function', () => { function Person(name) { this.name = name; } const BoundPerson = Person.bind({ ignored: true }); return new BoundPerson('Asha').name; });

attempt('7. class called without new', () => Counter('x'));
attempt('7b. this before super', () => { class A {} class B extends A { constructor() { this.x = 1; super(); } } return new B(); });

attempt('8. arrow field is per instance', () => new Counter('x').incArrow === new Counter('y').incArrow);
attempt('8b. prototype method is shared', () => new Counter('x').inc === new Counter('y').inc);

setTimeout(function () { console.log('timer callback, regular function, this is the timer:', this?.constructor?.name); }, 1);
setTimeout(() => console.log('timer callback, arrow function, this is module.exports:', this === module.exports), 2);

Run with Node.js v24.22.1 as js-169.js; two runs gave identical output. Output: 1. method called normally -> c1:1 1b. method extracted -> TypeError 1c. arrow field extracted -> c1:2 1d. bound method extracted -> c1:3 1e. wrapped in an arrow -> [ 'c1:4' ] 2. array callback, no thisArg -> TypeError 2b. array callback with thisArg -> [ 'c1:5' ] 4. regular method -> obj 4b. arrow as object method -> 0 keys on module.exports 4c. arrow inside a method -> [ 'obj' ] 4d. regular function inside a method -> [ undefined ] 5. bind then call with b -> a 5b. bind twice -> a 5c. call -> b 5d. new on a bound function -> Asha 7. class called without new -> TypeError 7b. this before super -> ReferenceError 8. arrow field is per instance -> false 8b. prototype method is shared -> true timer callback, regular function, this is the timer: Timeout timer callback, arrow function, this is module.exports: true

Key points

  • Regular functions: this comes from the call; arrow functions use this from the enclosing scope.
  • Extracted or callback methods lose their object; timers and array callbacks give undefined, the global object, or the timer.
  • bind fixes this for good; call and apply cannot override it, and new ignores it.
  • Arrow class fields give per-instance binding; object literal arrow methods do not get the object.
  • In derived constructors, use this only after super(); classes cannot be called without new.

Common mistakes

  • Passing obj.method as a callback and expecting this to be obj.
  • Using an arrow function as an object literal method.
  • Trying to change this on a bound function with call or apply.
  • Using this before super() in a derived constructor.

Follow-ups

  • What are the trade-offs of arrow functions as class fields?
  • How does new work on a bound function?
  • How do you pass the right this to a DOM event listener?

Tips

  • Start from the rule: the call site decides, except in arrow functions.
  • Give the three fixes: bind, arrow wrapper, arrow field.
  • Mention the memory cost of arrow fields.