Setting the stage for learning...
  1. Learn Langs
  2. Learn JS
  3. Class inheritance

Class inheritance

8 / 8

Provided by Learn Langs

Class inheritance

class Animal {

constructor(name) { this.speed = 0; this.name = name; } run(speed) { this.speed = speed; alert(${this.name} runs with speed ${this.speed}.); } stop() { this.speed = 0; alert(${this.name} stands still.); } }

let animal = new Animal("My animal");

Class inheritance

Here’s how we can represent animal object and Animal class graphically:…And we would like to create another class Rabbit\.

As rabbits are animals, Rabbit class should be based on Animal, have access to animal methods, so that rabbits can do what “generic” animals can do\.

The syntax to extend another class is: class Child extends Parent\.

Let’s create class Rabbit that inherits from Animal: Object of Rabbit class have access both to Rabbit methods, such as rabbit\.hide\(\), and also to Animal methods, such as rabbit\.run\(\)\.

Internally, extends keyword works using the good old prototype mechanics\. It sets Rabbit\.prototype\.\[\[Prototype\]\] to Animal\.prototype\. So, if a method is not found in Rabbit\.prototype, JavaScript takes it from Animal\.prototype\. For instance, to find rabbit\.run method, the engine checks \(bottom\-up on the picture\):

  • The rabbit object \(has no run\)\.
  • Its prototype, that is Rabbit\.prototype \(has hide, but not run\)\.
  • Its prototype, that is \(due to extends\) Animal\.prototype, that finally has the run method\.
  • As we can recall from the chapter Native prototypes, JavaScript itself uses prototypal inheritance for built\-in objects\. E\.g\. Date\.prototype\.\[\[Prototype\]\] is Object\.prototype\. That’s why dates have access to generic object methods\.

    !Image

    !Image

    !Image

    ← Class basic syntax