How to call base class constructor from child class in TypeScript?
How to call base class constructor from child class in TypeScript?
In TypeScript, to call a base class constructor from a child class, you use the extends
keyword to establish inheritance between the two classes. Then, within the constructor of the child class, you call the base class constructor using the super()
function. This approach ensures that the base class's constructor is executed, setting up the necessary properties or executing any logic defined there before the child class's constructor logic is executed.
Here’s a step-by-step explanation and an example:
Define the Base Class: First, you define your base class with its constructor. This constructor can initialize properties or include other setup logic that you want to be executed when an instance of the base class or any derived class is created.
Create the Child Class: Define the child class that extends the base class using the extends
keyword. This establishes a relationship where the child class inherits properties and methods from the base class.
Call the Base Class Constructor: Inside the constructor of the child class, use the super()
function to call the constructor of the base class. The arguments passed to super()
should match the parameters expected by the base class constructor.
Additional Logic in the Child Constructor: After calling super()
, you can add any additional initialization logic that is specific to the child class.
class Person {
constructor(private firstName: string, private lastName: string) {
console.log("Person constructor called");
}
getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}
}
class Employee extends Person {
private jobTitle: strin...
entry
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào