Introduction to JavaScript Inheritance

Introduction to JavaScript Inheritance

Before we dive in, I'll be assuming that you have prior knowledge on the following:

Pre-requisites: JavaScript Objects, constructor functions and basic object-oriented programming.

Creating a Class

Let's take a look at this Animal class:

class Animal {
  constructor(name, call, age, gender) {
    this.name = name;
    this.call = call;
    this.age = age;
    this.gender = gender;

  }

  speak() {
    console.log(`${this.call}!`);
  };
}

And we can create an example Animal object like so:

let scarlet = new Animal("Scarlet", "Meow", 2, "female");

The Animal class has a constructor function which contains all its properties that defines it. It also has a class method called speak(), which is defined below tha constructor function.

Using the new keyword, we can then instantiate a new Animal object called scarlet that has its properties and method.

Its properties and method can be accessed simply with dot notations:

scarlet.name;   //Scarlet
scarlet.speak();   //Meow!
scarlet.age;   //2
scarlet.gender;   //female

An Inheritance Example

So now, let's have an object that inherits properties and methods from the Animal class instead of just instantiating an Animal. Let's say we want to create a more specific animal, like a fish, which has additional properties.

An example Fish class would be:

class Fish extends Animal {
  constructor(name, call, age, gender, schooling) {
    super(name, call, age, gender);

    // properties and methods specific to Fish
    this.schooling = schooling;
  }
    swim(){
        if(this.schooling){
           console.log("I swim in a school!");
        } else{
           console.log("I swim solo!");
        }
    };
}

The extends keyword allow the Fish class to access properties from the Animal class by inheriting it. Under its constructor function, we indicate the properties the Fish is defined by: name, call, age, gender and schooling.

For name, call, age and gender, we inherit it from the Animal class and therefore we have to use the super() keyword to call the parent (Animal) constructor. The 'schooling' property and the swim() class method are not from the Animal class. They are created in the Fish class and are only accessible in this class.

So let's create a Fish object:

let dory = new Fish("Dory", "Just keep swimming", 1, "female", false);

And now its following properties and methods are defined from both the Animal and Fish class.

dory.name;   //Dory
dory.age;   //1
dory.gender;   //female
dory.speak();   //Just keep swimming!
dory.swim();   //I swim solo!

And that's the idea!

That's a simple illustration of a basic inheritance concept in Javascript. Let's move on to some more juicy stuff now!

Getters and Setters

In the event where we want to change the value of a class property or look up its value, we can have getters and setters.

Getters return the value of a specified property while setters update the defined property's value of a class object.

Let's create a getter and setter for the Fish class:

class Fish extends Animal {
  constructor(name, call, age, gender, schooling) {
    super(name, call, age, gender);

    // properties and methods specific to Fish
    this._schooling = schooling;
  }
    swim(){
        if(this._schooling){
           console.log("I swim in a school!");
        } else{
           console.log("I swim solo!");
        }
    };

    //getter and setter
    get schooling() {
       return this._schooling;
     }

     set schooling(newSchooling) {
       this._schooling = newSchooling;
     }
}

The "_" (underscore) in front of our schooling property is a convention to create a separate value to store our property for getting and setting values. With this, we now can get and set our schooling property by:

dory.schooling = true; //sets to true

console.log(dory.schooling) //gets the value of schooling

And that's all for now!

Thanks for reading this short introduction to inheritance. I hope you have inherited some knowledge! Sorry for the bad pun. There's definitely more about inheritance you can check out here. I highly recommend reading more and practice applying the concept into your projects. It is useful for when creating many different objects that shares similar properties. After all, it is more efficient to have less repetitive code. That's all for now, feel free to ask questions in the comments below. Cheers!

P.S. : Thank you for all the support on this blog. Some of you have messaged me, wanting to connect through Twitter, so I rebooted my old Twitter account in case any of you would like to follow me on Twitter: twitter.com/lo_victoria2666

Did you find this article valuable?

Support Articles by Victoria Lo by becoming a sponsor. Any amount is appreciated!

ย