TypeScript ``super()`` 调用基类构造函数


发布日期 : 2024-04-23 18:43:09 UTC

访问量: 10 次浏览

TypeScript 如何从子类调用基类构造函数

在本文中,我们将学习如何从子类调用基类构造函数。当一个类继承另一个类的属性时,它被称为子类,而被继承属性的类被称为父类,整个过程被称为继承。在继承中,子类获取基类或父类的属性。

您可以使用 super() 来从子类调用基类构造函数,这将执行基类的构造函数。

示例:

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 类的实例,并向其构造函数传递了两个参数 nameprofession,然后调用了 details() 方法,该方法会打印构造函数参数中提供的值。

示例2:

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 " + this.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