如何从 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());
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());
输出:
A is Android Developer
B is Web Developer
这里, Person类是我们的父类, Details类是我们的子类, Details类也继承了Person类。对于继承另一个类使用扩展关键字。 Details 类继承了 Person 类的属性。
现在在派生类中,我们使用了super() ,它将调用基类或父类的构造函数。在此之后,我们创建了一个 Details 类的实例,并将两个参数 name 和专业传递给它的构造函数,然后,我们调用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