One blueprint, many objects

INPUT · Slides

Using what you took over

01 / 06

Methods come over too

It is not only the constructor that comes over. Methods work as they stand as well.

There is no run written in the child class and yet b.run() works. When you call, it looks in the child class first and goes to the parent class if it is not there.

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

Result

red bike runs

02 / 06

this still points at whoever you called

The this inside a method written on the parent points at the child instance you called it on.

So the same run() puts out a different name per child. The work from the parent, the contents from the child.

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

Result

red bike runs
big truck runs

03 / 06

The order it goes looking in

Call a method and JS goes looking child, then parent.

1. it looks in the class of the one you called, for a method of that name
2. if there is none, it looks at the parent class
3. if there is still none, you get an error

Know this order and the "overwriting" machinery you learn next slides right in.

04 / 06

What happens if you write the same name on the child

Write a method on the child class with the same name as the parent's and, following the order, the child's is found first. Which means the child's version is used.

Put the shared behaviour on the parent and rewrite it only in the children that need to behave differently. Next lesson goes into this shape properly.

class Vehicle {  run() {    console.log("it runs");  }}class Bicycle extends Vehicle {  run() {    console.log("you pedal it");  }}new Vehicle().run();new Bicycle().run();

Result

it runs
you pedal it

05 / 06

Fix the parent and the children change

One shared method on the parent means that fixing it works on every child.

Nothing being left unfixed is inheritance's strength. Which also means that changing the parent affects the children, so give a little thought to whether something really belongs in the shared place.

06 / 06

What to put on the parent

The guide when in doubt is "is it true for every child?".

In the vehicle example, "runs" applies to every vehicle, so it can go on the parent. But "pedals" is only about bicycles, so it goes wrong up there.

Raising something to the parent just because two children happen to do the same work leaves you stuck when a third child arrives. Off you go.