What the heck is "this" keyword in javascript?

I want to know about this keyword in js. Please help me :frowning:

“this” on JavaScript works a lot differently than other programming languages. I can’t really explain it that well, but here’s a DevDocs that can explain it to the detail for you:
https://devdocs.io/javascript/operators/this

I’m assuming that you’ve already done some googling, but the explanations haven’t made sense. If you can tell us what parts you’ve found confusing we can probably help connect the dots. I know that I can’t do better than the many professional tutorials and explanations just off the top of my head.

1 Like

I saw plenty of videos about “this” keyword and read articles.
But the most confusing part is that when we use it in constructor function.

“this” keyword works totally differently on different environment. Like on a normal function declaration works differently than when it’s used on an Arrow function => declaration. It’s quite a really weird syntax.

Do you mean when variables are initialized or assigned with something like

this.name = "ArielLeslie";

?

yeah brother, what is the role of “this” keyword in this statement.

In that situation, think of this as the class saying “my” or “myself”. A class is a blueprint or template for creating as many of a thing as you need to. Each instance of that class uses this as a way to refer to it as an individual thing.

We could have a class for freeCodeCamp forum members. Our accounts all work the same way, but each of us has our own username. When the account is created, it needs to set that username. When the constructor says this.username = "ArielLeslie" it is saying “my username is ArielLeslie”.

1 Like

Does use of “this” have too anything else.

‘This’ differs from where you write it, for example if you are writing methods in a constructor object ‘this’ might refer to another method inside the constructor object. In other contexts ‘this’ could refer to the window object. If you are not sure about the value of it, just try to console.log it to see what it returns :smiley:

1 Like

Unfortunately for students, this can refer to different contexts depending on how and where it’s used. This is an extremely confusing part of learning JavaScript.

1 Like

The behavior of this in javascript is insane and a wart on the language. There’s no better resource for describing its weird behavior than YDKJS:

2 Likes