如何在 child class 中不使用 super 来初始化 parent class 属性?

How the parent class properties get initialised without using super inside the child class?

class Book{
  constructor(title,year){
    this.title = title
    this.year = year
  }
  getDetails(){
    return `Book ${this.title} is written in ${this.year}`
  }
}
class Magazine extends Book{
  // constructor(title,year,month){
  //   super(title,year)
  //   this.month = month
  // }
  
  fullDetails(){
    console.log(this.getDetails());
  }
}
const newBook = new Magazine('xxx','2022')
newBook.fullDetails() //output : Book xxx is written in 2022

在上面的代码中,Book 是 parent class,而 Magazine 是从 Book class 扩展而来的 child class。然后我通过传递标题和年份的值为 child class 创建了一个 object。我已经在 child class(Magazine) 中注释掉了构造函数和 super 方法,但是 parent class properties(title, year) 的属性仍然是初始化,我可以得到输出。谁能解释在 child class 中不调用 super 是如何实现的?提前致谢。

由于Magazine没有自己的构造函数,它继承了Book的构造函数,所以Book属性被初始化。

如果子class有自己的构造函数,你只需要调用super(),因为它会覆盖父class构造函数。

如果您没有在您的子 class 中定义构造函数,则会自动调用父构造函数。只有覆盖它,您才能控制其中发生的事情。

试试下面的操作,你会看到妈妈class的构造函数没有被调用。

class Book{
  constructor(title,year){
    this.title = title
    this.year = year
  }
  getDetails(){
    return `Book ${this.title} is written in ${this.year}`
  }
}
class Magazine extends Book{
  constructor(title,year,month){
    // Do nothing
    console.log('constructor is overidden');

 }
  
  fullDetails(){
    console.log(this.getDetails());
  }
}
const newBook = new Magazine('xxx','2022')
newBook.fullDetails()