Decoding the elusive 'this' in Javascript

Decoding the elusive 'this' in Javascript

Get a better understanding of the "this" keyword in Javascript

ยท

3 min read

When I first started learning javascript and came across the concept of this, I never understood it easily. It's hard for a beginner to grasp it at first because of the vague explanations out there. But it's a very important concept to know and can get easily confusing. I will explain about it in a simple way that could help many beginners.

The concept

Simply put, this refers to the object that is executing the current function

Let me elaborate. Say, there's an object with a method. If the method calls this then this refers to the object it's within.

let flower = {
  type: "Tulip",
  color: function() {
    console.log(this)
  }
}
flower.color()
// Object { type: "Tulip", color: color() }

Here, this is inside a method color which is inside the flower object. So as stated above, this refers to the object that is executing the current function which is the flower object.

Now let's take another example where the function isn't a part of an object like so,

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

What will this refer to in this case? There's no object to refer to as it's an independent function.
Here the object is the window/global object.

In the DOM, this would be the window object.
In Node, it refers to the global object.

Exceptions

Let's make this interesting. Let's use the same object above and tweak it a little.

let flower = {
  type: "Tulip",
  colors: ["yellow", "red", "white"],
  grow() {
    this.colors.forEach(function(color) {
      console.log(this.type, color)
      })
    }
}

flower.grow()

You would expect to see

Tulip yellow Tulip red Tulip white

But that's not the case here. Instead we see,

undefined yellow undefined red undefined white

But why this weird behavior?
There are 2 references of this here so let's address them both.

  • this.colors refers to the colors property inside the flower object. Hence it can be easily accessed and the array is traversed.
  • this.type is called inside a callback function. If you look closely, you see that the function inside the forEach loop is a callback function. It is not a method.
    So even though it exists inside an object, it behaves like a regular function because that's what it is. And this refers to the global/window object as seen earlier.

Summary

  • this refers to the function it is executed in.
  • It behaves differently based on the context of the function execution.
  • A method references its this to the object calling it.
  • A regular function references its this to the global object.

    And that's what this is all about. In my next article I will explain the different ways to change the context of this.

That's all for this article. I hope it was helpful and gave you some insight into this. ๐ŸŽ‰๐ŸŽ‰