This in JavaScript

21st Jun 2017

Are you confused by the this keyword in JavaScript? It confuses everyone in the beginning, so don’t worry about it. You’re not alone.

But that doesn’t mean you can go on without understanding this forever. It is used so much in JavaScript and in tutorials everywhere that you need to grasp what this is sooner or later. Once you understand this, you’ll realize that it’s much simpler than you think it is.

By the end of this article, you would have demystified this for yourself. You’ll know what it is, what it does and how to use it.

So, what is this?

this is a keyword whose value changes depending on how a function gets called. There six different ways where this can take on new values. They are:

this in global context

this in object construction

this in an object method

this in a simple function

this in an arrow function

this in an event listener

You may wonder what this is in each context and why there’s a need to change this in the first place. To answer your question, let look at how this changes in each of the six contexts.

This in a global context

When this is called outside of any function, in a global context, this defaults to the Window object in the browser.

console.log(this) // Window

This defaults to window object in browsers

Usually, you wouldn’t use this in a global context anyway, so the value of this here doesn’t really matter. Let’s move on to the next context.

This in object construction

When you create a new instance of an object with the new keyword, this refers to the instance.

A third way to change the value of this within any function is to use either bind, call or apply. We’ll look at bind later in the article, and call and apply another time. But first, let’s go through the final context — event listeners.

Wrapping up

this is a crucial keyword in JavaScript. It appears in many JavaScript frameworks, so you have to know what it does.

In this article, you learned about the six different contexts where this takes on different values. You also learned how to change the this context with functions like bind. Additionally, you also learned to remove event listeners properly.

That’s all you need to know about this. Just master the concepts taught in this article and you won’t ever get confused anymore.

If you have any questions, just hit me up in the comments below :)

(If you liked this article, I'd appreciate it if you could share it. 🤗)