DEV Community

Cover image for Understand "this" in JavaScript
Shreya Prasad
Shreya Prasad

Posted on

Understand "this" in JavaScript

"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.

Console with

I learn better when I visualise concepts. That's why I've created few illustrations to simplify this.

this inside window object
this in a global context.

Functional context:

Now what happens if this is used inside a function?

this inside a function
this 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?

this inside a custom object

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:

Top comments (0)