The 'this' keyword

The 'this' keyword

Modern JavaScript Series

Introduction to this

The this keyword is often a source of confusion for new JavaScript programmers. In this blog post I'll explain what this is, and how it changes depending on use.

This always refers to an object. The object referenced changes depending on the execution context, ie. how you call the function. In other words this references the object of which the function is a property. Let's take a look at what this means:

const user = {
    firstName: "Christian",
    lastName: "Holm",
    fullName() {
        return `${this.firstName} ${this.lastName}`;
    }
}

user.fullName(); // "Christian Holm"

In the above example, this is used inside a method on the object "user". That's why it points to the user object. But if you were to use this inside a regular function it will behave differently:

function whatIsThis() {
   console.log(this);
}

whatIsThis(); // returns the global window object

The reason why is because we're calling whatIsThis() from the global object. It's inferred that what we're really calling is window.whatIsThis() and therefore this refers to the window object. However, if we use the strict mode this will return undefined instead of the window object.

You can use this easy rule to remember: this points to whatever is to the left of the function being called. So user.fullName() points to the user object, but calling a regular function just points to the global object (you can visualize it as window.function()).

Arrow functions

Arrow functions behave differently than regular functions. They don’t have their own this context. Instead they get this from their surrounding scope/parent (also known as lexical scope). So if you were to use an arrow function in our previous example, you would get window or undefined depending on whether or not you use strict mode:

const user = {
    firstName: "Christian",
    lastName: "Holm",
    fullName: () => {
        return this;  // simplified the example to show 'this'
    }
}

user.fullName(); // Window

Bind()

Finally let's talk about bind() and what it does. Bind() creates a new function and binds an object to it. We can then reference the bound object with this. Let's look at an example:

let john = {
  first: "John",
  last: "Doe"
}

let susan = {
  first: "Susan",
  last: "Smith"
}

function printName() {
  console.log(`${this.first} ${this.last}`);
}

let johnFunction = printName.bind(john);
johnFunction(); // "John Doe"

let susanFunction = printName.bind(susan);
susanFunction(); // "Susan Smith"

Summary

This changes depending on the execution context. Use the 'left of the dot' rule to remember what object the this keyword points to. And remember that arrow functions don't have their own this context, but instead uses its parent context.