TypeScript 如何从子类调用基类构造函数
在本文中,我们将学习如何从子类调用基类构造函数。当一个类继承另一个类的属性时,它被称为 子类 ,而被继承属性的类被称为 父类 ,整个过程被称为 继承 。在继承中,子类获取基类或父类的属性。
您可以使用 super() 来从子类调用基类构造函数,这将执行基类的构造函数。
示例:
Javascript
class Person {
// Properties of the Person class
Name: string;
Profession: string;
// Constructor of Person class
constructor(name: string, profession: string) {
this.Name = name;
this.Profession = profession;
}
}
class Details extends Person {
// Properties of the class
Name: string;
Profession: string;
// Constructor of the Details class
constructor(name: string, profession: string) {
// Calling the base class constructor
super(name, profession);
// Setting the properties
this.Name = name;
this.Profession = profession;
}
details(): string {
return this.Name + " is " +
this.Profession;
}
}
// Creating an object
var data =
new Details("A", "Android Developer");
var data2 =
new Details("B", "Web Developer");
// Accessing the function details()
// and printing
console.log(data.details());
console.log(data2.details());
输出:
A is Android Developer
B is Web Developer
在这里, Person 类是我们的父类,而 Details 类是我们的子类,也继承了 Person 类。通过使用extends关键字来继承另一个类。Details类继承了Person类的属性。
现在在派生类中,我们使用了 super() ,它会调用基类或父类的构造函数。在此之后,我们创建了Details类的实例,并向其构造函数传递了两个参数name和profession,然后调用了details方法,该方法会打印构造函数参数中提供的值。
示例2:
Javascript
class Square {
// Properties of the Square class
side: number;
// Constructor of the Square class
constructor(side: number) {
this.side = side;
}
}
class Area extends Square {
// Properties of the Area class
side: number;
// Constructor of the Area class
constructor(side: number) {
// Calling the base class constructor
super(side);
// Setting the properties
this.side = side;
}
// Returns the area of square
area(): string {
return "The area of Square is " + t
his.side * this.side;
}
}
// Creating object of class Area
var data = new Area(7);
// Getting the property and
// printing the value
console.log(data.area());
输出:
The area of Square is 49