Tech Interview RoomStudy guides

JavaScript

How does `this` work in JavaScript?

Intermediate · 2 min read · Lesson 6 of 12 in JavaScript

this is decided by how a function is called, not where it is written. Arrow functions are the exception.

The rules, from highest priority

  1. new binding: new Fn() sets this to the newly created object.
  2. Explicit binding: fn.call(obj), fn.apply(obj, args) or fn.bind(obj) set this to obj.
  3. Implicit binding: obj.method() sets this to obj (the object before the dot).
  4. Default binding: a plain call fn() gives undefined in strict mode (modules and classes are always strict) or the global object in sloppy mode.

Arrow functions

Arrow functions have no own this. They use this from the surrounding scope at creation time, and call/bind cannot change it. That is why arrows are ideal for callbacks inside methods, and wrong as object methods.

Losing this

Passing a method as a callback detaches it from its object: setTimeout(obj.method) calls it as a plain function. Fix with obj.method.bind(obj), an arrow wrapper, or a class field arrow function.

Example

js
const user = {
  name: 'Asha',
  greet() { return `Hi ${this.name}`; },
  greetLater() { setTimeout(() => console.log(this.greet()), 0); }, // arrow keeps this = user
};

console.log(user.greet());          // Hi Asha (implicit)
const loose = user.greet;
// loose();                         // TypeError in strict mode: this is undefined
console.log(loose.call({ name: 'Ravi' })); // Hi Ravi (explicit)
user.greetLater();                  // Hi Asha

Follow-up questions interviewers ask

Try answering each one before you open it.

What does bind return and can you bind twice?

bind returns a new bound function with this (and optionally leading arguments) fixed permanently. Binding a bound function again does not change this; only extra arguments are added. The one thing that overrides a bound this is calling it with new.