whatstheoutput_

#89: A plain function nested inside a method

Topic: this · Difficulty: ★★★

const obj = {
  name: 'Ann',
  outer() {
    function inner() {
      return this;
    }
    console.log(this.name);
    console.log(inner() === globalThis);
  },
};
obj.outer();

Output

Ann
true

Why

this is scoped per function call, not inherited by nested functions the way closed-over variables are. Calling obj.outer() sets outer's this to obj, so this.name correctly reads 'Ann'. But inner is an ordinary nested function, and it is called as a bare function call — inner(), with no receiver — so it gets its OWN this, computed independently from outer's. In non-strict mode (what node -e uses), a bare call sets this to the global object rather than undefined, so inner() === globalThis is true. In strict mode, that same bare call would instead set this to undefined.

More this puzzles

Play today's puzzle →