DEV Community

Rangga Putra
Rangga Putra

Posted on

What is this in Javascript

This is confusing

this in Javascript is quirky, unlike in other programming languages where this is usually quite straightforward as it is a reference to the object where the property or method is invoked, in Javascript this's value is varied by its usages. Let's take a look.

 

This in a regular function

this in regular function refers to the execution context of the codes in the example shown below this value is the Node.js's global object if the function is run in the browser then the value is the browser's window object.

 

This in strict mode

One thing to keep in mind while working with this is whether you are using the strict mode or not, introduced in ES5, strict mode is a restricted version of JavaScript, it's supposed to help you write secure codes. In strict mode the global execution context is undefined.

 

This in an event handler

this when evaluated inside the callback of an event listener refers to the element where the event is triggered.

 

This in an object

In object, this refers to the object which calls the function. In the example below introduce is a method of person object.

 

This in an arrow function

this inside an arrow function is where it gets confusing. unlike regular function, where this is bound to the object that calls the function, the arrow function uses something called lexical scoping which basically looks for this value in their enclosing parent and inherits it. In the example below, this inside the introduce method inherits its value from the person object which has this value of the window object, while this inside the doIntroduction inherit its value from casualIntroduce method since it's a regular function its bind this value to person object.

 

This in a constructor function

If you use this in a constructor function and invoke it with the new keyword it will create a new object from this defined inside the function and this will refer to the said object.

 

This can be whatever you want

But if all of the usages mentioned above are confusing to you and you have had enough of it and don't want to guess what value of this in your codes, you can explicitly set the value yourself using bind, call or apply method. In the examples below you can use bind to create a new function which has this value of the object that you passed as the first argument if you don't want to create a new function you can use call or apply, the difference between the two is that with apply you pass the function's second arguments as an array.

Top comments (0)