One blueprint, many objects

INPUT · Slides

Building on a class you already have

01 / 04

Two classes that are nearly the same

Say you wrote separate blueprints for "vehicle" and "truck". Holding a name, running along — you end up writing the shared part into both.

Having to fix two places when you want to change the shared part is a nuisance, and fixing only one and having them drift apart is the frightening bit.

02 / 04

Take it over with extends

Write class Child extends Parent { } and you get a class that takes over the parent class's contents as they stand. This is called inheritance.

Even with the child class's { } empty, the parent's constructor works properly. So hand values to the new and the properties get set up exactly as the parent wrote.

class Vehicle {  constructor(name) {    this.name = name;  }}class Bicycle extends Vehicle {}const b = new Bicycle("red bike");console.log(b.name);

Result

red bike

03 / 04

What we call the parent and the child

The one being taken over from is the parent class and the one taking over is the child class (also called superclass and subclass).

Taking over is one-way. The child can use the parent's things, but the parent knows nothing of the child. This matters, so it comes up again later.

class Vehicle {  constructor(name, wheels) {    this.name = name;    this.wheels = wheels;  }}class Truck extends Vehicle {}const t = new Truck("big truck", 6);console.log(t.name);console.log(t.wheels);

Result

big truck
6

04 / 04

The shared part can live in one place

However many children you make from the same parent, the shared part lives in one place: the parent.

And one place to fix. Take it that inheritance's chief aim is fewer places to fix, rather than less to write. Off you go.

class Vehicle {  constructor(name) {    this.name = name;  }}class Bicycle extends Vehicle {}class Truck extends Vehicle {}const b = new Bicycle("red bike");const t = new Truck("big truck");console.log(b.name);console.log(t.name);

Result

red bike
big truck