CodeBlanks Logo Icon CodeBlanks

The this context

JavaScript course · Intermediate · Lesson 4/134

Learn that arrow functions bind this lexically and what that means.

Lexical this

Inside an arrow function, this is bound to the scope where the arrow is defined. This is called lexical this. Classic functions bind this dynamically based on the caller, while arrows inherit it from the surrounding scope.

const obj = {
  name: "Alex",
  show() {
    const inner = () => console.log(this.name);
    inner();
  }
};
obj.show(); // "Alex"

The arrow keeps the this of the show method, so this.name works.

Losing this in a callback

When a classic function is passed as a callback, it loses its this binding; this is a common bug. An arrow keeps this intact.

function Timer() {
  this.count = 0;
  setInterval(function() {
    this.count++; // wrong: this is window
  }, 1000);
}

The same code with an arrow keeps this correct:

setInterval(() => {
  this.count++; // correct: this is Timer
}, 1000);

Exercise Arrow callback that preserves this

The counter object's start method calls setInterval. Make the callback an arrow and increment this.count. Do not use a classic function.

Show example solution
const counter = {
  count: 0,
  start() {
    setInterval(() => {
      this.count++;
    }, 1000);
  }
};

Test yourself

  1. What does this refer to inside an arrow?

    • The object that calls the function
    • The outer scope where the arrow is defined
    • A new empty object
    • Always the window object
    Show answer

    The outer scope where the arrow is defined — Correct. An arrow takes this lexically from the outer scope.

  2. The arrow that preserves this

    setInterval(() ____ { this.count++; }, 1000);
    Show answer
    setInterval(() => { this.count++; }, 1000);
  3. Match the this behavior

    arrow function
    this is lexical
    classic function
    this is dynamic
    callback bug
    this is lost
  4. What does the call return?

    const obj = {
      v: 10,
      show() {
        const f = () => this.v;
        return f();
      }
    };
    obj.show();
    • undefined
    • 0
    • 10
    • throws an error
    Show answer

    10 — Correct. The <code>show</code> method binds this to obj; the arrow inherits it, so <code>this.v</code> = 10.

All lessons in Intermediate