Syntax

Users can follow the syntax below to use this keyword generally. Users can observe how we can access the variable or invoke the method using this keyword.

this.var_name;
this.method_name();
console.log(this.var_name);

In TypeScript, this keyword refers to the global object if it’s not used inside any class or method. Even if we use this keyword inside the function, it refers to the global means window object. Also, we can use this keyword inside the callback function of the class method.

Below, we will learn to use this keyword in different scenarios.

Example1

In the example below, we have created the demo class, which contains the ‘y’ property. Also, we defined the display() method inside the demo class. The display() method prints the message with the value of the property y. Here, the important thing is that we access the property y using this keyword. In the display() method, this keyword refers to the demo class.

After that, we created the object of the demo class and invoked the display() method by taking the demo_object as a reference which prints the message shown in the output.

// Creating the demo class
class demo {
   y = 10;
   // Defining the display method inside the demo class
   display() {
      console.log("This is display method of demo class ");
      console.log("The Value of the Property y of the demo class is " + this.y)
   }
}
// Creating the object of the demo class
var demo_object = new demo();

// Invoke the object of the demo class
demo_object.display();

Output

The above code will produce the following output −

This is display method of demo class
The Value of the Property y of the demo class is 10

We will follow the below steps in the next example −

Example 2

In this example, this keyword refers to the car class. As show_type() is virtually copied to the car class, we can access it using this keyword. In simple terms, we have accessed the method of the parent class to the child class using this keyword.

// Creating the vehicle class
class Vehical {

   // Defining the vehicle_type property
   vehicle_type: string = "medium";

   // Show_type method of the Vehicle class.
   show_type() {

      console.log("This is inside the show_type method of the Vehicle class");
      console.log("The vehicle type is " + this.vehicle_type);
   }
}
// Creating the car class which is the base class of the Vehicle class.
class car extends Vehical {

   // Defining the display method inside the car class
   show_message() {
      this.show_type();
      console.log("This is show_message method of car class ");
   }
}
// Creating the object of the car class
var car_object = new car();
// Invoke the object of the demo class
car_object.show_message();