2

I am learning JS and I am told that if I want to extend a class I need to use a constructor and super(). But when I was experimenting I discovered that I can extend the class without. I tried to find an explanation on the internet but couldn't find one. Can somebody explain to me? Thanks

class Person {
  constructor(name, email, address) {
    this.name = name;
    this.email = email;
    this.adress = address;
  }

}

class Employee extends Person {
  getName() {
    return (
      "Hi!," +
      this.name +
      " who has " +
      this.email +
      " as email and lives in " +
      this.adress
    );
  }
}

const newEmployee = new Employee("Ahmed", "ahmed@test.com", "Beverly Hills");

console.log(newEmployee.getName()); *// Hi!,Ahmed who has ahmed@test.com as email and lives in Beverly Hills*
Ahmed
  • 41
  • 4
  • Using `super` in your constructor is needed only if you define a constructor that does something different. If you define a constructor in `Employee` and call `new Employee` the *that* constructor gets called, not the one in `Person`. – VLAZ Sep 30 '19 at 10:09

3 Answers3

2

Super method is used to call parent's constructor. You can use it if you need it (using the logic of your parent class in your derived class), but it's not mandatory. You can create a class without constructor, but it will use a default one

constructor() {}

For the derived class, if you don't specify a constructor, it will use

constructor(...args) {
  super(...args);
}
Yushox
  • 162
  • 12
2

As per the documentation for constructor's, on Default constructors.

For derived classes, the default constructor is:

 constructor(...args) {
    super(...args);
 }

which means that the default constructor already has the call for super in it, along with the default dependencies of its base class (...args in your case is name, email, address).

If you define your own constructor for your derived class Employee, you will have to call the super() with the said dependencies.

As to why do you have to call super, you may read more from another answer by loganfsmyth.

Alex Pappas
  • 2,377
  • 3
  • 24
  • 48
0

you may not need super() if you are not adding a new property to the sub class. but if you need to add a new property to the sub class, you have to use call super()