CodePark/ questions / this & binding
START PRACTICINGPRACTICE
Frontend question · JavaScript › this & binding

What does this log?

const obj = {
  value: 42,
  getArrow() {
    return () => this.value;
  },
  getRegular() {
    return function () {
      return this?.value;
    };
  },
};
const a = obj.getArrow();
const r = obj.getRegular();
console.log(a(), r());
42 undefined

The arrow function takes this from getArrow. getArrow was called as obj.getArrow(), so this is obj and a() returns 42.

The inner regular function is called later as a plain
r(). So its this uses the default binding: undefined in strict mode, or the global object otherwise. value is not found there, so r() returns undefined.

The tempting option "42 42" is wrong because the regular function does not remember that it was created inside
getRegular. Its this depends only on how it is called.