DEV Community

Pravin kumar
Pravin kumar

Posted on

“this” keyword in javascript

Understanding about “this” keyword in javascript saves you a lot of time debugging the code later. So, let’s start with understanding what’s a global context.

What is this global context?

The global context refers to the global object that contains all the default functions and fields. In browser the global context is the window object. By default the “this” keyword refers to the global object when used outside of the function.

Function Invocation vs Function definition

Function invocation means the instant when the function is called with arguments.Test()

Function definition means creating a function and assigning it to a variable but not calling it. A function which is not assigned to a variable is also a definition but we can only invoke it later if it’s assigned to a variable. There is a way to invoke a function immediately when defining it, but I won’t confuse you with those details now. This is const Test = function(){} function definition.

this inside a function

Inside a function the this keyword is used to refer to the caller of the function. Let’s assume that an object has a key “data” and a function definition as a value. If the data function is called from the object, then this keyword will point to this object inside the data function.
obj.data() here the this keyword will refer to obj. However, when the same data function is referenced by another variable and invoked like this var t = obj.data;
t()
. Then the value of this will be the window object or the global context inside the data function.
The above example is the common way of passing callbacks and major source for bugs if the callback has this keyword in it.

This is my first post and I don’t want to go on ranting about this anymore. Hope someone finds this useful 😉.

Top comments (1)

Collapse
 
pravinkumar95 profile image
Pravin kumar

You are right. Wasn't thinking of recommending "this" when I wrote this post. I have encountered many edge cases using "this" and this post was to help others understand the potential bugs that can be caused by the usage of "this". IMO, the better way to develop is to use typescript and develop in a functional or declarative way all the way avoiding "this".