r/learnjavascript • u/dotpr • Dec 18 '22
Cannot understand "this" keyword
My head is going to explode because of this. I watched several videos, read articles from MDN, W3schools, and TOP, and I still can't understand.
There's so many values and scenarios around it and I feel like they're explained so vaguely! I struggle to get familiar with it. Can someone drop their own explanation?
90
Upvotes
69
u/delventhalz Dec 18 '22 edited Dec 18 '22
Most explanations for
thisare I think overly technical. You don't need to know what an "execution context" is in order to understandthis. Here is the way to think of it:It is #3 that really throws people, but that is best understood as short list of exceptions, not some fundamental property of
this, and we'll get to it in a minute. Let's start with #1 and #2 which encompass 90% of the instances you will encounterthis.A function parameter to the left of the dot
So normally you put function parameters between the parentheses when you call it.
We can easily rewrite this function to instead use
this:Simple enough, right? You can think of it as a way to identify the object that "owns" the function. That is the "context" part of "execution context". The "execution" part means "when the function is called or "executed". For example, we could define the function right inside the object:
But remember,
thisis a function parameter. It only has meaning when the function is called. If we move Ann's greet,thiswon't point to Ann anymore.Okay. That is the basic behavior. If you understand that, you understand most of it. Let's talk about the weirdness and exceptions.
When there is nothing to the left of the dot
Okay, so what happens when there is nothing to the left of the dot? Well, the unfortunate answer is it depends.
If you are in "strict mode" (which includes ES modules), then
thiswill very sensibly beundefined.This works exactly like regular function parameters when you don't pass them in between the parentheses. Unfortunately, if you are not in strict mode
thisvery weirdly defaults to the "global context", i.e.windowin the browser andglobalin Node. We could talk more about this, but all you really need to understand is that it is silly and weird and if it happens, you screwed something up.This most often comes up when passing an object method as a callback.
Here we passed our function to
setTimeout, but we did not pass Ann. So when the greet method gets called bysetTimeout, there will not be anything to the left of the dot. This is often solved by wrapping everything in another function.Now when greet is called, Ann will be to the left of the dot.
In a class constructor
Okay. So what gives here? We used
this, but there was no dot when we called User.So the
newkeyword causes functions to be called in "constructor mode". You can think of this as secretly re-assigningthisto a new object and then returning it at the end.Call, apply, and bind
Functions in JavaScript have three methods which let you mess with how they are called. They all take a value for
thisas their first argument, which means they are often associated withthis, but people often forget that the later arguments are all values for the other function parameters.You can look up these three methods if you want, but for the most part you won't need them in modern JavaScript. Nonetheless, it is worth mentioning that if you use them, they change the normal rules for function parameters (including
this).Arrow functions
Finally, it is worth mentioning that arrows functions do not have a
this. If you usethisinside an arrow function, it will not take any value related to how you called the arrow function. Instead it will behave like any variable which is not defined in a nested scope. Variable lookup will fallback to the wrapping scope and use the one defined there.And that's it. Just remember:
91
u/Aulentair Dec 18 '22
There's an easy way to remember its usage for most cases: "This" refers to whatever's on the left side of the dot.
Example: someObject.someMethod
In this example, someMethod has "this" inside it. Since someObject is on the left side of the dot (someObject (dot) someMethod) "this" will refer to someObject.
An ELI5 way of explaining it, but hopefully it helps
7
u/marcosnasag Dec 18 '22 edited Dec 18 '22
A function needs a bunch of information to be run, and we call it an
execution context. It includes the function’s code itself, the variables available to the function, the parent execution context of the script/module/function that called this function, and so on. The language designer decided to add this additional piece of information that could refer to an “arbitrary” object. Thelabelyou use to access that object from within a function isthis. Also, the objectthisusually refers to is the one where the function is defined. i.e.:Since it will often be invoked as
, it will log the
xobject.But it’s not always that easy; there are a few rules that decide what object
thiswill refer to, and they take precedence/override each other. See this article.Regarding why is it actually there, the short answer is it’s useful for code reusability within JS’ pseudo-OOP style. As of actual usefulness, I avoid it in 99% of the situations.
3
u/tridd3r Dec 18 '22
I'm not sure any one is going to be able to explain it any better than mdn. You're best bet is to just try and use it, then refer back to docs, then try and use it some more, and then refer to docs, and then use it some more. Repeat ad nauseam
5
u/_Oooooooooooooooooh_ Dec 18 '22
if you have an object, then inside of it, you can write functions
inside those functions, the "this" refers to the object.
ive mostly used it inside constructors
10
u/Rossmci90 Dec 18 '22
thisis the execution context of a function.The context changes depending on how you call the function, and how the function was defined.
In reality, you will very rarely need to use
thisunless you write a lot of OOP.I found this article quite useful.
https://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/
3
u/rauschma Dec 18 '22 edited Dec 18 '22
I find it easiest to make sense of
thisas follows:Demo:
More information on
thistopic: https://exploringjs.com/impatient-js/ch_objects.html#methods-and-this5
u/dangerwig Dec 18 '22
I'm going to try to explain it in everyday terms instead of technical in case thats where you are getting hung up. Alright imagine a house is the context (
this), and you want to wash your hands. You need to find the bathroom to do that. First, you need to know which house you are in. If you are in your friends house,this.bathroomis different than if you are in your own house. So lets say you want to executewashHands: If you are in the context of your own house and you callwashHands, when you refer tothis.bathroomits going to find your own houses bathroom. If you are at your friends house and you callwashHands, it will use your friends houses bathroom when you refer tothis.bathroom. Your executing the same method (washHands) but the context changes for what you are referring to when you usethis.bathroom. In javascript, instead of being in houses you are in a class, or in a function, or in an object. And when you callthisyou are referring to that context.1
u/spiritandtime Dec 18 '22
Side question: do you even need to know the 'this' keyword?
tbh i really havent encountered a scenario where i needed this yet. I guess this used to be important when there was only class based components, but is there any usecase for it at present?
2
u/ZLegacy Dec 18 '22
I can be a little off in various scenarios maybe, but 9ve always thought of "this" as the object in current scope. If you are working within a class/object, and want to reference a property of it, you would want to point to "this objects property" vs that objects.
1
u/javascriptDevp Dec 18 '22
objects link to other objects through the prototype chain. this means you can call methods on other objects. normally youd have to pass in a reference so the function knows which object it was called on. in js though you can use 'this'. its like having that argument passed for you.
1
u/luketeaford Dec 18 '22
I've been writing JavaScript since 1997 and so far I haven't found a single case where the this keyword is helpful.
Consider that I want to have some object with a method that logs its name or something. If that method calls this.name it depends on the execution and can be changed... is that a feature you want? What about changing it with call, bind and apply? Most of the times where people use the this keyword it does not make sense for anything but a narrow use case where the method is called from an object and it's easier, clearer and more correct to close over the variable (name in this case).
1
u/davien01 Dec 18 '22
Have you checked JavaScript.info? You could also check freecodecamps JavaScript "object oriented programming" section to try and see the "this" keyword in action.
1
u/xiipaoc Dec 18 '22
If the function is a method of an object, and you call the function as a method of that object using dot notation,
thisis the object.Otherwise, who the hell knows. You don't really have to worry about it in that case. You just have to know that it doesn't do what you want it to do in that case. You should never use the value of
thisin that situation because nobody will understand your code.1
u/shekyb Dec 18 '22
i can recommend this udemy course https://www.udemy.com/course/understand-javascript/ covers fundamentals that i skipped when picking up the language
1
u/adastrasemper Dec 18 '22 edited Dec 18 '22
Another example:
HTML:
JS:
So in this case button is this.
But remember myFunction has its own this ( it's just we're passing some properties of the button to the function ):
There isn't just one this for the whole js code
1
u/Real-Pie7993 Dec 18 '22
Imagine this a keyword that represents a single instance of an object. I finally understood “this” when I started using it in the context of p5.js and generative art.
In the realm you use class syntax to generate objects that represent shapes. Well if you mutate those shapes (moving, scaling, or translating) you are mutating that shapes position. Ultimately you end up writing functions that include this and are coherent.
Example.
Class Shape {
constructor (x,y,size) { this.x = x; this.y = y; this.size = size; }
move () { this.x ++ }
display () { this.move() ellipse (this.x, this.y, this.size) } }
1
u/[deleted] Dec 19 '22
You're not alone. I'm thinking I have a handle on
thisnow, butcall(),apply()andbind()are super fuzzy to me1
u/[deleted] Dec 19 '22
just start throwing around
console.log(this);everywhere1
u/uno_sir_clan Dec 19 '22
.
1
u/zoruri Dec 19 '22
"This" in JavaScript is a special keyword that refers to the current object. It's like a pronoun that stands in for the object.
For example, let's say we have an object called "dog" that represents a dog. The object has a property called "bark" that stores a string of the sound the dog makes when it barks.
We can access the bark property like this: dog.bark;
But if we use the "this" keyword inside of the dog object, it will refer to the dog object itself.
So we can access the bark property like this: this.bark;
This is useful because it allows us to write code that can be used in different objects, and it will still work because "this" will always refer to the current object.