Search code examples
javascriptclassprototypal-inheritance

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

In the above code, Book is the parent class and the Magazine is the child class which extends from Book class. Then I have created an object for the child class by passing the values for the title and year. I have commented out the constructor function and the super method in the child class(Magazine) but still, the properties of the parent class properties(title, year) are initialized and I can get the output. Can anyone explain how this is possible without calling super in the child class? Thanks in advance.


Solution

  • If you don't define a constructor in your child class, the parent constructor is automatically called. Only if you override it can you take control of what happens in it.

    Try what follows, you'll see the constructor of the mother class is not called.

    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()