In TypeScript, constructor functions are used to initialize an object when it is created. There are two main approaches to defining constructor functions:
- Using ES6 class syntax (Modern approach).
- 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, theconstructor
takes amessage
argument, which is used to initialize thegreeting
property. - The
greet()
method uses thegreeting
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 theGreeter.prototype
, which means all instances ofGreeter
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:
-
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.
- Uses
-
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).
- Uses a regular function to define the constructor, and methods are added to the