DEV Community

loading...

Tired of Guessing What 'this' Is Referring To?

guin profile image Angelika Jarosz ・2 min read

What is this?

If you are new to JavaScript it is only a matter of time before you run into the concept of the this keyword. The this keyword is the JavaScript context object in which the current code is executing. When JavaScript code is executing, it is running within a specific execution context. When a browser first loads a script, it is in the global execution context. However, once a function is called a new execution context is formed and pushed onto the call stack.

At first determining the value of this might feel a little like magic and have you throwing console.log()'s in your code. However, there are only a few rules that you can go through to figure out what this is referring to. The most important thing to first remember is that the value of this depends on how a function is called. Looking at where the function is defined will not help you.

Rules for determining the value of this:

First we look to see if the new keyword is used when calling the function. If new is used this inside the function will refer to the brand new object created when new runs Object.Create() under the hood.

Second we see if apply, call, or bind are used when calling the function. this inside the function will refer to the object that is passed in as the argument to apply, call, or bind.

Third, if a function is called as a method, such as obj.method() — this will refer to the object that the function is a property of.

Otherwise this is the global object. In a browser, it is the window object. If in strict mode ('use strict'), this will be undefined instead of the global object.

One thing to note is that ES6 arrow functions ignore all the rules above. They do not have their own this, so this is determined lexically. This means that JavaScript will look to its surrounding parent scope to determine what this is referring to.

Why is this even important?

If we think about why we write functions in general we see that functions make it easy to encapsulate and reuse logic. The this keyword lets us decide what context we want when we invoke a function. By using this we can reuse functions or methods within different contexts or with different objects.

If you have any questions, comments, or feedback - please let me know. Follow for new weekly posts about JavaScript, React, Python, and Django!

Discussion

pic
Editor guide
Collapse
jdforsythe profile image
Jeremy Forsythe

I'd advise to avoid writing code that uses this altogether. It avoids issues with juniors misunderstanding and promotes less complex code. I don't think I've used it on purpose in the last handful of years.

Collapse
kadajett profile image
Jeremy Stover

Not using this excludes you from a vast amount of logic. Modern JavaScript is centered around classes where it is necessary to use this in most cases. Maybe you have some technique I'm not aware of. I'd love to hear it if so!

Collapse
guin profile image
Angelika Jarosz Author

Introducing less complexity is always great! I do think its an important concept of the language to understand though.

Collapse
nssimeonov profile image
Templar++

Things should be kept simple and obvious. Obvious code is great. You can change a feature years later without trying to understand it for a day and then fixing bugs, because you missed a few small details.

This is why "this" is a terrible feature in JS.

On the other hand JS has so many issues like this and that keeps away people, who try to write software without even finishing their first book and not having any idea what they do. So I call it even.

kadajett profile image
Jeremy Stover

While the react community is moving towards functional components, most companies still use class based components. I guess you could just use anon functions in the class, but then you lose the ability to see the name while debugging, unless you do a bunch of extra code.

jdforsythe profile image
Jeremy Forsythe

I don't write React code. I'm a full stack JS dev and avoid classes like the plague, when possible. Sure, every JS dev should understand the keyword, and I didn't mean to suggest otherwise. I just don't find many reasons to ever use a class beyond creating new Error classes or using a library that requires it. There are so many ways to accomplish similar things.

Also, it's not just the React community moving toward functional programming. I'd bet there are as many companies using functional techniques as classes. Ever use Array.map? Or lodash.filter? Promises and Observables are (basically) Monads. We got arrow functions and Array.prototype methods specifically because of the rise in FP in JS. I highly suggest Eric Elliot's series on Medium about FP, especially the "Forgotten History of OOP" medium.com/javascript-scene/the-fo...

I'm not a FP fanboy, either. It's just another tool that is useful sometimes. And if I find a place I need a class beyond what I said above, I would use it. I just can't think of many use cases where I need one.

Collapse
filisko profile image
Filis Futsarov

Perhaps some code examples would help?

Collapse
guin profile image
Angelika Jarosz Author

Definitely! I might add some if/when i have the time this week. Alternatively, if anyone wants a deeper dive with some great code examples I would suggest this post by Tyler McGinnis
tylermcginnis.com/this-keyword-cal...

Collapse
silvestricodes profile image
Jonathan Silvestri

Well written Angelika!

Collapse
guin profile image
Collapse
jsmanifest profile image
jsmanifest

Great read!

Collapse
paddyh4 profile image
Pradeep Chavan

Thanks. Informative.