"This keyword refers to the object it belongs to."
You must have heard this line almost everywhere, but never fully understood what it actually means? Let's understand this.
this is nothing more than a reserved keyword in JavaScript that points to the object it is present inside.
Global Context:
Alone, this refers to the global object. Global object is nothing but the window object created by the JavaScript engine in the browser.
I learn better when I visualise concepts. That's why I've created few illustrations to simplify this.
Functional context:
Now what happens if this is used inside a function?
It still point to window object! But why?
Because that function is present globally, so technically it is present inside window object. So, this refers to the global object, i.e. window.
So far this has been pointing to window object only. Nothing has changed. So when does it return a different value that we all have been reading about?
Custom Object Context:
Let's see what happens if this is used inside an object that we create?
In a method, this refers to the person object. It means that this will point to the object inside which we are using "this" keyword.
To summarise:
Globally, this will point to window object because this is being used inside window object. But if we create an object of our own and use this inside that object, then it will point to that particular object.
Additional Info:
- We will talk about the behaviour of this inside an arrow function in another blog.
- Tricky questions around this keyword
Top comments (0)