StruggleCode101: “this” Is Really A Thing.
Today we are going to be talking about this.
That’s right, I still yappin’ about JavaScript.
Let me say this (not this) right off the bat, this is similar to self.
If you haven’t read about self yet, pause here, read, and then come back.
Unfortunately the subject is not as straightforward as one may think.
Personally, I would have chosen a different keyword...but what do I know? I just started coding in March.
Time to actually talk like I understand some things.
this = the object that is executing the present function.
If the function is a method in an object, this is talking about the literal object.
If the function is NOT apart of an object, this is talking about the global object.
const beer = {
category: 'Stout',
drink() {
console.log(this); // {category: "Stout", drink: f}
}
};
The beer object has a property called category.
The beer object also has a method called drink.
When you see the beer object in the console this is talking about about the property and the method. (drink is a method in the object)
const beer = {
category: 'Stout',
drink() {
console.log(this);
}
};
function drinkBeer() {
console.log(this);
}
drinkBeer();
When you call this, it’s is talking about whatever is in the “window”. You can also call this a global object.
Please understand that this by default is talking about a global object.
When a method is inside of an object, this is talking about both the object and the method.
Not that I made an example for this (not this) instance but, when you call a function with the new operator...this is talking about the new (not new) instance.
I am sure reading this a few times will help something click in your head...it defiantly clicked as I was typing.
I am also very sure I will have a more intelligent way of communicating my understanding a little later...until then...this will do.