this in JavaScript

By

Learn how the value of this changes in JavaScript depending on where you use it, from undefined in strict mode to the object it is bound to inside a method.

~~~

this is a keyword that has different values depending on where it’s used.

Not knowing this tiny detail of JavaScript can cause a lot of headaches, so it’s worth taking 5 minutes to learn all the tricks.

this in strict mode

Outside any object, this in strict mode is always undefined.

Notice I mentioned strict mode. If strict mode is disabled (the default state if you don’t explicitly add 'use strict' on top of your file ), you are in the so-called sloppy mode, and this - unless some specific cases mentioned here below - has the value of the global object.

Which means window in a browser context.

this in methods

A method is a function attached to an object.

You can see it in various forms.

Here’s one:

const car = {
  maker: 'Ford',
  model: 'Fiesta',

  drive() {
    console.log(`Driving a ${this.maker} ${this.model} car!`)
  }
}

car.drive()
//Driving a Ford Fiesta car!

In this case, using a regular function, this is automatically bound to the object.

Note: the above method declaration is the same as drive: function() {…, but shorter:

const car = {
  maker: 'Ford',
  model: 'Fiesta',

  drive: function() {
    console.log(`Driving a ${this.maker} ${this.model} car!`)
  }
}

The same works in this example:

const car = {
  maker: 'Ford',
  model: 'Fiesta'
}

car.drive = function() {
  console.log(`Driving a ${this.maker} ${this.model} car!`)
}

car.drive()
//Driving a Ford Fiesta car!

An arrow function does not work in the same way, as it’s lexically bound:

const car = {
  maker: 'Ford',
  model: 'Fiesta',

  drive: () => {
    console.log(`Driving a ${this.maker} ${this.