Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending class in JS without constructor or super()

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", "[email protected]", "Beverly Hills");

console.log(newEmployee.getName()); *// Hi!,Ahmed who has [email protected] as email and lives in Beverly Hills*
like image 800
Ahmed Avatar asked Apr 18 '26 07:04

Ahmed


1 Answers

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);
}
like image 95
Yushox Avatar answered Apr 19 '26 21:04

Yushox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!