In TypeScript, constructor functions are used to initialize an object when it is created. There are two main approaches to defining constructor functions:

  1. Using ES6 class syntax (Modern approach).
  2. Using function-based constructor syntax (Traditional JavaScript approach).

Example 1: Constructor Function Using ES6 class Syntax

class Greeter {
  greeting: string; // Property declaration
 
  // Constructor function to initialize the property
  constructor(message: string) {
    this.greeting = message; // Initializing 'greeting' property with the provided message
  }
 
  // Method to return the greeting message
  greet() {
    return "Hello, " + this.greeting;
  }
}
 
// Creating an instance of the Greeter class
let greeter: Greeter;
greeter = new Greeter("world");
 
// Calling the greet method
console.log(greeter.greet()); // "Hello, world"

Key Points (Modern ES6 Class Syntax):

  • The constructor is a special method used to initialize the object when it is created.
  • In the Greeter class, the constructor takes a message argument, which is used to initialize the greeting property.
  • The greet() method uses the greeting property to return a greeting message.

Example 2: Constructor Function Using Traditional JavaScript (Function-based Syntax)

let Greeter = (function() {
  // Constructor function
  function Greeter(message: string) {
    this.greeting = message; // Initialize the 'greeting' property
  }
 
  // Adding method to the prototype
  Greeter.prototype.greet = function() {
    return "Hello, " + this.greeting; // Return greeting message
  };
 
  return Greeter; // Return the constructor function
})();
 
// Creating an instance using the constructor function
let greeter;
greeter = new Greeter("world");
 
// Calling the greet method
console.log(greeter.greet()); // "Hello, world"

Key Points (Traditional Function-based Constructor Syntax):

  • The constructor function Greeter is defined as a regular function (not a class).
  • The method greet is added to the Greeter.prototype, which means all instances of Greeter will inherit this method.
  • You create an instance using the new keyword, just like with ES6 classes, but this time the function is used directly as a constructor.

Differences between ES6 Classes and Function-based Constructor Functions:

  1. ES6 Class Syntax:

    • Uses class to define a constructor function and methods inside the class.
    • More structured and modern, with support for inheritance and other features.
  2. Function-based Constructor Syntax:

    • Uses a regular function to define the constructor, and methods are added to the prototype.
    • This approach is closer to the way JavaScript worked before ES6 and provides flexibility in some cases (e.g., using closures).