Skip to the content

Composition

JavaScript · Unit 13: Inheritance

Inheriting says "is a": a dog is an animal. But often the relationship is "has a": a car has an engine. That isn't inherited. The car keeps an Engine object in a property, and uses it through there. This is called composition.

class Engine {
  constructor(hp) {
    this.hp = hp;
  }
  start() {
    return "vroom";
  }
}
class Car {
  constructor(hp) {
    this.engine = new Engine(hp);
  }
}
const c = new Car(120);
console.log(c.engine.hp);
console.log(c.engine.start());

Prints

120
vroom

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. Multiple choice

    In which pair is the relationship "has a" and not "is a"?

  2. 2. Predict the output

    What does this code print?

  3. 3. Find the bug

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

  4. 4. Complete the code

    Fill in the blank so the bike warns people using its horn.

  5. 5. Predict the output

    A playlist has songs. What does it print?

  6. 6. Multiple choice

    Emma wrote class Car extends Engine. What's the problem?

  7. 7. Put the lines in order

    The remote has a battery cell, which it gets when it's created. Put the program in order so it shows the charge. Cell and the constructor fit on one line.

  8. 8. Predict the output

    The lamp gets a new bulb. What does it print?

  9. 9. Find the case that fails

    teamAverage(goals) signs a Player for each number in the array and returns the team's average goals, or 0 if there are no players. Which call makes it fail?

  10. 10. Predict the output

    A team has players, and one of them is the goalie. 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 →