this keyword. First of all, let’s understand what is this.
What is “this”?
In simple terms, we can say that
this refers to the object that is executing the current function. Even though the definition sounds very simple, there are different scenarios that the value of
this keyword assigned differently. Let’s take a look at each scenario, separately so that will help you to understand
this more easily. Following are the topics that are covered in this article
- Regular function and
- Function constructors and
- Object, methods and
- Call and Apply methods
- Bind method
Regular functions and “this” keyword
In regular function calls,
this always refers to the global object. A global object is an object that always exists in the global scope. In browsers, this global object is known as a window object. Since
testFunction is a regular function Line A will prints
true on the console.
Function constructors and
Line B , if we invoked the function with the
new keyword, then the function acts as a constructor function and it will return a new object. So that
this will refer to the newly created object. Following console outputs will help you to understand this scenario properly.
The output of Line A :
The output of Line B :
Object, methods, and this keyword
When a method invoked,
this keyword will simply refer to the object, where that method belongs to. If we consider the above code example,
checkThis method of john object is referring to the jhon object.
Let's do a small modification to the above code.
According to the previous explanation
this inside methods refer to the same object where the method belongs to. But if you run the above code, you will see that
Lina A is printing
false to the console. The reason behind this behavior is when someone invoked the
checkThis method of jhon object, it will do a regular function call
print() inside the method. We know that when there is a regular function call,
this referring to the
Call and Apply methods
bind . These methods allow us to handle the value of
this manually. Let’s understand the use of the
call method by referring to the following code.
The first argument of the
call method is assigned as the
this object for that particular function. In
Line A we are passing
tharind as the first argument of
Person.displayDetails.call() method, so that
tharindu object will be assigned as the
displayDetails function. That is the reason that we are having the above output. The only difference between the
apply method is , that
apply method is accepting an array of arguments as the second parameter.
bind method will return a new function and the
this object of new function will refer to the first argument of
Ok, that is all about
this . If this article did help you to clarify “this”, please feel free to share this with your friends.