What is the use of this keyword in TypeScript?



The “this” keyword is one of the most used keywords in TypeScript. For beginner TypeScript programmers, it’s complex to understand how this keyword works, but they will learn by the end of this tutorial. In this tutorial, we will learn to use this keyword in TypeScript.

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.

Example 1

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();

On compiling, it will generate the following JavaScript code −

// Creating the demo class
var demo = /** @class */ (function () {
   function demo() {
      this.y = 10;
   }
   // Defining the display method inside the demo class
   demo.prototype.display = function () {
      console.log("This is display method of demo class ");
      console.log("The Value of the Property y of the demo class is " + this.y);
   };
   return demo;
}());
// 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 −

  • Step 1 − Create the Vehicle class, which contains the vehicle_type property and show_type() class method.

  • Step 2 − Inside the show_type() method, access the vehicle type using this keyword and print it with the message.

  • Step 3 − Create the car class, which extends the Vehicle class. It means the car is the base class, and the Vehicle is the parent class. Here, the car class is the base class of the Vehicle class which means all methods and properties of the Vehicle class are virtually copied to the car class, and we can also access it using the object of the car class.

  • Step 4 − Using this keyword, define the show_message() method, which calls the show_type() method of the car class.

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();

On compiling, it will generate the following JavaScript code −

var __extends = (this && this.__extends) || (function () {
   var extendStatics = function (d, b) {
      extendStatics = Object.setPrototypeOf ||
      ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
      function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
      return extendStatics(d, b);
   };
   return function (d, b) {
      extendStatics(d, b);
      function __() { 
         this.constructor = d; 
      }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
   };
})();
// Creating the vehicle class
var Vehical = /** @class */ (function () {
   function Vehical() {
      // Defining the vehicle_type property
      this.vehicle_type = "medium";
   }
   // Show_type method of the Vehicle class.
   Vehical.prototype.show_type = function () {
      console.log("This is inside the show_type method of the Vehicle class");
      console.log("The vehicle type is " + this.vehicle_type);
   };
   return Vehical;
}());
// Creating the car class which is the base class of the Vehicle class.
var car = /** @class */ (function (_super) {
   __extends(car, _super);
   function car() {
      return _super !== null && _super.apply(this, arguments) || this;
   }
   // Defining the display method inside the car class
   car.prototype.show_message = function () {
      this.show_type();
      console.log("This is show_message method of car class ");
   };
   return car;
}(Vehical));
// Creating the object of the car class
var car_object = new car();

// Invoke the object of the demo class
car_object.show_message();

Output

The above code will produce the following output −

This is inside the show_type method of the Vehicle class
The vehicle type is medium
This is show_message method of car class

Example 3

In this example, we have created the normal object in TypeScript. We defined the website_name and language properties inside the object. Also, we defined the test() method, which returns the string.

Inside the test() method, we used this keyword to access the object properties. Here, this keyword refers to the current object. After that, we invoked the test() method by taking the obj as a reference and storing the string, which the method returns to the message variable.

var obj = {
   // Defining the object properties
   website_name: "TutorialsPoint",
   language: "TypeScript",

   // Defining the test() method for the object
   test(): string {
      return (
         this.website_name +
         " is a best website to learn " +
         this.language +
         " Programming language."
      );
   },
};
// call the test() method obj and store return value to message.
let message: string = obj.test();

// printe the message
console.log(message);

On compiling, it will generate the following JavaScript code −

var obj = {
   // Defining the object properties
   website_name: "TutorialsPoint",
   language: "TypeScript",
   
   // Defining the test() method for the object
   test: function () {
      return (this.website_name +
      " is a best website to learn " +
      this.language +
      " Programming language.");
   }
};
// call the test() method obj and store return value to message.
var message = obj.test();

// printe the message
console.log(message);

Output

The above code will produce the following output −

TutorialsPoint is a best website to learn TypeScript Programming language.

Example 4

In the example below, we have created the test class and defined the month's array of numbers. After that, we used the filter() method to filter all months greater than 7. We have passed the callback function as the first argument of the filter() method and this keyword as a second parameter.

We have accessed the value property of the class using this keyword inside the callback function of the filter() method. We can learn to use this keyword inside the callback function from this example.

// Creating the test class
class test {

// Defining the value property
value: number = 7;

// Defining the months array
months: Array<number> = [1, 4, 7, 10, 12, 6, 9];

// Filter the all months whioh are greater than 7
// Use this keyword as a pameter of the method
filtered_months = this.months.filter((month) => {
   return month > this.value;
}, this);
}
// Creting the object of the test class
let test_obj = new test();
console.log("Filtered months are " + test_obj.filtered_months);

On compiling, it will generate the following JavaScript code −

// Creating the test class
var test = /** @class */ (function () {
   function test() {
      var _this = this;
      
      // Defining the value property
      this.value = 7;
      
      // Defining the months array
      this.months = [1, 4, 7, 10, 12, 6, 9];
      
      // Filter the all months whioh are greater than 7
      // Use this keyword as a pameter of the method
      this.filtered_months = this.months.filter(function (month) {
         return month > _this.value;
      }, this);
   }
   return test;
}());
// Creting the object of the test class
var test_obj = new test();
console.log("Filtered months are " + test_obj.filtered_months);

Output

The above code will produce the following output −

Filtered months are 10,12,9

We learned four different examples in this tutorial to use this keyword in TypeScript. The “this” keyword refers to the object or class we use. However, we can use this keyword as a global object, but that is not good practice. So, it is recommended to use this keyword inside a particular scope, like an object or class.


Advertisements