العودة إلى الدورة

Inheritance with 'extends' and 'super'

JavaScript: الدورة الكاملة للمبتدئين من 'الصفر إلى الاحتراف'

73. Inheritance with extends and super

Inheritance allows one class (the child/subclass) to inherit the properties and methods of another class (the parent/superclass). This enables code reuse and models 'is-a' relationships.

The extends Keyword

javascript class Animal { constructor(name) { this.name = name; } eat() { console.log(${this.name} is eating.); } }

// Dog extends Animal, inheriting 'name' and 'eat()' functionality class Dog extends Animal { bark() { console.log('Woof!'); } }

const myDog = new Dog('Fido'); myDog.eat(); // Fido is eating. myDog.bark(); // Woof!

The super Keyword

If the child class needs its own constructor, it must call super(arguments) first. super calls the constructor of the parent class.

javascript class Puppy extends Dog { constructor(name, breed) { super(name); // Calls Animal's constructor (setting 'this.name') this.breed = breed; } fetch() { console.log(${this.name} (a ${this.breed}) is fetching.); } }

const puppy = new Puppy('Wag', 'Beagle'); puppy.fetch();