Sitemap
Sarah

Sarah

Cracking JavaScript’s ‘this’ Keyword

5 min readFeb 17, 2019

--

Learning about what the keyword this in JavaScript can be a perplexing and frustrating process. It never seems to mean the same thing in different contexts, thus can be a little daunting at first.

With this article, I hope to clear up some of the confusion that may come with the mysterious, ever-changing this.

The first thing to understand is that this takes different values depending on where it is used. For example, it takes different meanings in the following cases:

  1. By itself
  2. Inside a method
  3. Inside a function
  4. Inside an event
  5. With call(), apply(), and bind()

The most important thing to note before reading further is that the this keyword allows you to decide which OBJECT it should refer to.

1. By Itself

When used by itself, this refers to the global object, or the window.

That means that this will have access to any variables that are defined in the global scope:

One exception to this is when you are in ‘use strict’ mode. Read more about that here.

2. Inside a Method

When used within a method, this refers to the Object that called it.

Press enter or click to view image in full size

Here, getMenu is a method that is defined inside the bobsBurgers Object. What that means is that this no longer refers to the global object, but instead refers to the specific Object that called it.

This this goes into the bobsBurgers Object and has access to the menu by calling this.menu.

3. Inside a Function

When this is used inside a function, depending on how a function is called, it can refer to either the window or an object.

For example:

Press enter or click to view image in full size

The first function we call, getIngredients(), is not attached to any object. It is in the global scope, which means that it only has access to the ingredients that are in the global scope. The this in this context refers to the window.

The second time we call getIngredients(), we invoke it with the Object specialBurger. Now, this refers to specialBurger and gets its properties from that Object.

4. Inside an Event

As we have seen before, JavaScript can manipulate elements in the DOM (shameless plug read my last blog 😏). When we add event listeners to elements on the page, we are able to call other functions to run.

Let’s say we have a button on our page:

Now, using an Event Listener, when that button is clicked, we call a function removeBob().

If this is used inside that function, it refers to the element that raised the event. In this case, it refers to the button!

Get Sarah’s stories in your inbox

Join Medium for free to get updates from this writer.

This is possible because elements on a page are actually also objects.

Here is the result:

Now you don’t!!

5. call(), apply(), and bind()

JavaScript provides us with methods that allow us to borrow functions and provide different this values.

  • call() and apply()

Let’s say we have an Class Constructor for SpecialBurger which takes in two parameters name and ingredients. The constructor uses this to define whatever is passed into the arguments.

Below this constructor, we also have a function serve() that uses this to console.log a string.

Let’s create a SpecialBurger:

Right now, if we tried to call serve() on eggBurger, we get a TypeError:

Press enter or click to view image in full size

This is because right now, serve()’s this is referring to the global object, or the window.

Fortunately, call() allows us to invoke functions with values for this that we can control:

Press enter or click to view image in full size
(change highlighted)

If we tell our serve() function to call the Object eggBurger, it allows serve()’s this to refer to eggBurger!

We could even pass in an argument into our function serve().

Press enter or click to view image in full size
changes highlighted

This is where apply() comes in. call() and apply() work exactly the same, except apply() can only take function arguments in the form of arrays:

Press enter or click to view image in full size

Now we know that we can explicitly set this and then immediately execute the function call. We can also borrow functions and delay calling them for later!

  • bind()

We have an Object gene and a function greeting():

Let’s save this in a variable named geneGreeting and use bind to get the right Object:

If we check to see what geneGreeting is we get an entire function:

Press enter or click to view image in full size

bind() has attached the gene Object to greeting(), and now we can call the function anytime we want:

Press enter or click to view image in full size

While this can seem confusing and unpredictable at first, once you master it, it is an extremely useful and powerful tool. You got this!!

--

--