One blueprint, many objects

INPUT · Slides

Swapping out behaviour you took over

01 / 04

When what you took over does not fit

The run written on the parent shows "runs". But for the bicycle alone you want it to say "glides along".

Add a method with a different name just for that child and the calling side ends up "changing the name it calls depending on who it is". You want to avoid that.

02 / 04

Rewrite it under the same name

Write a method on the child class with the same name as the parent's and that one gets used for that child. This is called overriding.

The calling side still just writes run(). Only the behaviour has been swapped out.

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

Result

red bike glides along

03 / 04

The parent side does not change

What gets overridden is that child alone. The parent class's method is still there as it was, and other children are unaffected.

Rather than "delete the parent's and rewrite it", think "look at a different one when it is that child".

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

Result

plain car runs
red bike glides along

04 / 04

Remember the order it looks in

Call a method and it looks in that child class first, going to the parent if there is none — that was the order.

Overriding is only using that order. If the child has the same name, it is found there without going as far as the parent.

Off you go.