javascript · level 3 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
lets one class inherit everything from another.
An ebook is a product with a download. Rather than copy every method, write class Ebook extends Product. This is : the child class gets all of the parent's methods for free.
A child with its own constructor must call first, which runs the parent's constructor. To change an inherited method, it by writing one with the same name. Inside it, super.label() still reaches the parent's version, so you can build on it.
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
label() { return `${this.name}: £${this.price}`; }
}
class Ebook extends Product {
label() { return `${super.label()} (download)`; }
}
const shelf = [new Product("Mug", 8), new Ebook("Recipes", 5)];
for (const item of shelf) { console.log(item.label()); } Ebook has no constructor of its own, so JavaScript passes its arguments straight to the one in Product.
guess first
A parent method meets a child override. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} makes a sound`; }
intro() { return `I am ${this.name}. ${this.speak()}.`; }
}
class Dog extends Animal {
speak() { return "Woof"; }
}
console.log(new Dog("Rex").intro());
your turn
Your turn. Build a bike from a vehicle.
Pass the number of wheels a bike has up to the parent constructor, then choose a colour for your bike.
fix it
The warning never appears. Can you fix it?
- Read the error name. Which line in the
Warningconstructor runs first? - In a child class,
thisdoes not exist untilsuper(...)has run. - Move
super(text);abovethis.level = "high";, then press run.
nailed it
your classes have families now. :D
extendsgives a child class all of the parent's methods.- Call
super(...)before usingthisin a child constructor. - Override by reusing a name;
superstill reaches the original.
new words in your collection
- inheritance
- extends
- super
- override
This lesson isn’t saved. A free account remembers every lesson you finish.