01 / 04
One blueprint, many objects
INPUT · Slides
Adding something the child alone can do
02 / 04
Just write it inside the child class
It is written like any method you have written so far. Just put it inside the child class's { }.
An instance of the child ends up with both the methods it took over from the parent and the ones that are its own.
class Vehicle { constructor(name) { this.name = name; } run() { console.log(`${this.name} runs`); }}class Truck extends Vehicle { load() { console.log(`${this.name} loads up`); }}const t = new Truck("big truck");t.run();t.load();Result
big truck runs big truck loads up
03 / 04
this works in a child's method too
Even from a method written on the child class, you can read a property the parent set up with this. The load above using this.name is the proof.
Once it has come over, take it that it is yours.
04 / 04
Taking over is one-way
The thing to watch is the other direction. An instance made from Vehicle has no load(). What you add on the child does not reach the parent.
The guide when in doubt is this.
- applies to every child → write it on the parent
- belongs to that child alone → write it on the child
Off you go.