Skip to main content
04

How is this determined?

MediumJavaScriptthisFunctions

How is the value of this determined in JavaScript? Where do call, apply, bind and arrow functions fit in?

TL;DR

this is decided by how a function is called, not where it's defined. Arrow functions are the exception: they have no this of their own and use the this of the surrounding scope.

Key points

Rules, from highest priority to lowest:

  1. new: this is the newly created object.
  2. Explicit: fn.call(obj, a, b), fn.apply(obj, [a, b]) or fn.bind(obj) set this to obj. bind returns a new function that always uses that this.
  3. Method call: obj.method() sets this to obj (whatever is left of the dot).
  4. Plain call: fn() gives undefined in strict mode (and in modules and classes), or the global object in sloppy mode.
  • Arrow functions ignore all four rules and capture this lexically. call, apply and bind can't change it.
  • In DOM listeners with a regular function, this is the element.

Example

js
const user = {
  name: 'Dana',
  greet() {
    return this.name
  },
}
user.greet() // 'Dana'
const greet = user.greet
greet() // undefined: called without a receiver, so this is lost
greet.call(user) // 'Dana'

class Timer {
  seconds = 0
  start() {
    setInterval(() => this.seconds++, 1000) // arrow keeps the instance's this
  }
}

Common follow-ups

  • Why do callbacks lose this? Passing obj.method passes only the function. Use an arrow wrapper, bind, or a class field arrow function.
  • call vs apply? Same thing; call takes arguments one by one, apply takes an array.

What interviewers look for

Tip

"It depends on the call site", the four rules in order, and arrow functions as the lexical exception.

  • Red flag: "this is the object where the function was written."

Was this helpful?

Related questions