Skip to the content

extends

JavaScript · Unit 13: Inheritance

Sometimes a class is a more specific version of another: a dog is an animal. With extends, the child class gets everything from the parent class without copying it: its constructor and its methods.

Dog writes nothing between its braces, and it can still eat.

class Animal {
  constructor(name) {
    this.name = name;
  }
  eat() {
    return `${this.name} eats`;
  }
}
class Dog extends Animal {}
const rex = new Dog("Rex");
console.log(rex.eat());

Prints

Rex eats

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    Fill in the blank so Scooter is a child class of Vehicle.

  2. 2. Predict the output

    What does this code print?

  3. 3. Multiple choice

    Savings was written like this: class Savings extends Account {}. What does an object made with new Savings(100) have?

  4. 4. Predict the output

    What does this code print?

  5. 5. Predict the output

    Cat and Dog are children of the same parent. What does it print?

  6. 6. Find the bug

    This program should print "Rayo drifts". Which line has the bug?

  7. 7. Predict the output

    What does this code print?

  8. 8. Put the lines in order

    Put the program in order so Kira, a Cat, introduces herself with the method she inherits from Pet.

  9. 9. Multiple choice

    A store's program has an Employee class. Which one makes sense as a child class of Employee?

  10. 10. Predict the output

    Some products in the cart are on sale. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →