Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Inheritance with extends and Using super() | Classes
Advanced JavaScript Mastery
course content

Зміст курсу

Advanced JavaScript Mastery

Advanced JavaScript Mastery

1. Classes
2. DOM Manipulation
3. Events and Event Handling
4. Asynchronous JavaScript and APIs

bookInheritance with extends and Using super()

What Is Class Inheritance?

JavaScript uses the extends keyword to establish this relationship between classes. A child class can add its own properties and methods or override those from the parent class.

Think of a child class as a specialized version of the parent class. If the parent class is a blueprint for a car, the child class could represent a specific type of car, like an electric car. The electric car inherits the basic functionality (wheels, steering) but can add or modify features (battery, charging system).

How to Use the extends Keyword

The extends keyword is used to make one class inherit from another class. The child class inherits all the properties and methods of the parent class.

1234567891011121314151617181920
class Animal { constructor(name) { this.name = name; } makeSound() { console.log(`${this.name} makes a sound.`); } } // Child class extending the Animal class class Dog extends Animal { bark() { console.log(`${this.name} barks!`); } } const dog = new Dog('Rex'); dog.makeSound(); // Output: Rex makes a sound. dog.bark(); // Output: Rex barks!
copy

In this example, the Dog class extends the Animal class, inheriting the makeSound() method from the parent class. The Dog class also adds its own bark() method.

Working with the Constructor in a Child Class

When you create a child class, it often needs to initialize its own properties as well as those of the parent class. This is done through the constructor method. However, to ensure that the parent class is properly initialized, you must use the super() function to call the parent class's constructor.

Important: When a child class has a constructor, it must call super() before accessing this, or else an error will occur.

Using super() to Call the Parent Class Constructor

The super() function is used to call the constructor of the parent class from within the child class constructor. This ensures that any properties or logic defined in the parent class constructor are correctly initialized before adding new functionality in the child class.

1234567891011121314151617181920212223242526
class Animal { constructor(name) { this.name = name; } makeSound() { console.log(`${this.name} makes a sound.`); } } // Child class with its own constructor class Dog extends Animal { constructor(name, breed) { // Call the parent class constructor using super() super(name); this.breed = breed; } bark() { console.log(`${this.name}, the ${this.breed}, barks!`); } } const dog = new Dog('Rex', 'German Shepherd'); dog.makeSound(); // Output: Rex makes a sound. dog.bark(); // Output: Rex, the German Shepherd, barks!
copy

In this example, we have a base class called Animal with a constructor that initializes the name property and a method makeSound that logs a generic sound message. The Dog class extends Animal, adding its own constructor that accepts both name and breed as arguments. Inside the Dog constructor, the super() function is used to call the parent class's constructor, ensuring that name is set correctly. Additionally, Dog introduces a new method, bark, that logs a message specific to the dog’s breed. When we create a new Dog instance named Rex of the German Shepherd breed, we can call both makeSound and bark, showcasing the inherited and new behavior.

Key Points When Using extends and super()

Inheritance: The extends keyword allows the child class to inherit properties and methods from the parent class.

Constructor in Child Class: When defining a constructor in the child class, always use super() to call the parent class constructor.

Accessing this: You must call super() before accessing this in the child class constructor.

Method Overriding: You can override parent class methods in the child class by defining a method with the same name. You can also use super.methodName() to call the parent class method from within the child class if needed.

Example: Overriding Methods and Using super()

Sometimes, you might want to override a method from the parent class in the child class, but still call the parent class method as part of the new logic. You can do this using super.methodName().

1234567891011121314151617181920212223242526272829
class Animal { constructor(name) { this.name = name; } makeSound() { console.log(`${this.name} makes a generic sound.`); } } class Dog extends Animal { constructor(name, breed) { super(name); this.breed = breed; } // Override the makeSound method makeSound() { // Call the parent class's makeSound method super.makeSound(); console.log(`${this.name}, the ${this.breed}, barks loudly.`); } } const dog = new Dog('Rex', 'German Shepherd'); dog.makeSound(); // Output: // Rex makes a generic sound. // Rex, the German Shepherd, barks loudly.
copy

In this example, the Dog class overrides the makeSound method but still calls the parent class's makeSound method using super.makeSound(). This allows the child class to extend the parent class's behavior without completely replacing it.

Real-World Example: Employee and Manager Classes

Let's consider a scenario where we have an Employee class and a Manager class that extends it. The Manager class adds new functionality on top of the base Employee functionality.

12345678910111213141516171819202122232425262728
class Employee { constructor(name, position) { this.name = name; this.position = position; } getDetails() { return `${this.name} works as a ${this.position}.`; } } class Manager extends Employee { constructor(name, position, department) { // Call the parent class constructor using super() super(name, position); this.department = department; } getDetails() { return `${super.getDetails()} They manage the ${ this.department } department.`; } } const manager = new Manager('Alice', 'Manager', 'Sales'); console.log(manager.getDetails()); // Output: Alice works as a Manager. They manage the Sales department.
copy

In this example, the Manager class extends the Employee class, adding a new department property. The getDetails() method in the Manager class calls the parent class method using super.getDetails() and then adds its own department-specific information.

1. What does the `extends` keyword do?
2. In a child class, why do we use `super()` in the constructor?
3. What will the following code output?
What does the `extends` keyword do?

What does the extends keyword do?

Виберіть правильну відповідь

In a child class, why do we use `super()` in the constructor?

In a child class, why do we use super() in the constructor?

Виберіть правильну відповідь

What will the following code output?

What will the following code output?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 14
some-alt