DEV Community

Sarthak
Sarthak

Posted on

This keyword in Javascript

The this keyword in javascript behaves a bit differently than other languages. That is why it confuses a lot of people. If you are one of them, then this post is a great start for you to know about it.

So what is this and what is its value?

This is a property of an execution context (global, function, or eval) that, in non–strict mode, is always a reference to an object and in strict mode can be any value.

In most cases, the value of this is determined by how a function is called(runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called.

Alt Text

Let’s now see what is the value of this in different contexts -

Global Context

In the global execution context (outside of any function), this refers to the global object whether in strict mode or not.

Alt Text

Function Context

For Functions, the value of this is determined by how they are called.

For functions called directly without setting the value of this, this defaults to the global object, which in the browser is the window object.

Alt Text

However, in strict mode, the value of this is set to undefined if it is not set while entering an execution context.

Alt Text

Calling a function with a particular value of this

We can call a function with a specific this value using the call and apply method.

Call()
The call() method calls a function with a given this value and arguments provided individually.

Alt Text

Apply()
The call() method calls a function with a given this value and arguments provided as an array.

Alt Text

Bind()
The bind method creates a new function with the same body and scope as the function on which it is called, but this of the new function is permanently bound to the first argument of the bind method.

Alt Text

Arrow Functions

In arrow functions, the value of this is equal to the enclosing lexical context’s this value. So, In global code, it will be set to the global object.

Alt Text

Alt Text

Note: We cannot set this value of arrow functions even using call, apply and bind methods.

As an object method

When a function is called as a method of an object, its this is set to the object the method is called on.

Alt Text

I hope this post gives you a fair amount of idea about how this works in JavaScript.

Top comments (0)