DEV Community

Cover image for Object-Oriented Programming in JavaScript (Part III)
Oscar Luna
Oscar Luna

Posted on • Updated on

Object-Oriented Programming in JavaScript (Part III)

So I know I've been jumping back and forth between subjects in Object-Oriented Programming, but I did some dumb things yesterday that led me to reset to a prior repository and losing the intended post for yesterday. Today I'm feeling much better, and I am going to skip on down to one of the more awesome yet complex aspects of object-oriented programming, and that is Inheritance.

Inheritance

Last time I brushed a bit on the global Object and how every object has a prototype object under the hood that is derived from a superclass Object, and this prototype chain goes on back and back and back, linking one object under the hood to another until you reach the end of the chain where the prototype is null.
JavaScript makes it possible for us to take a class and build a new class out of it with the same properties as the old class, but! We can take the properties of the new subclass and redefine them, since they are objects. This passing down of properties from a previous object is called inheritance.

Take, for example, a React Class Component. Under the hood React has a defined class Component from which other class-based components React can extend its properties to. We use extends to indicate that our components should derive directly from React.Component, rather than Object.prototype. A class from which new classes are derived from is called the superclass, and the derived classes the subclass. But more on React later. For now, let's look at this example:

'use strict';

class Vehicle {
  constructor (height, width) {
    this.height = height;
    this.width = width;
  }
}

class Car extends Vehicle {
  constructor(sideLength) {
    super(sideLength, sideLength);
  }
  get area() {
    return this.height * this.width;
    }
  set sideLength(newLength) {
    this.height = newLength;
    this.width = newLength;
  }
}

var Ford = new Car(8);
Enter fullscreen mode Exit fullscreen mode

We initialize the App instance here by calling super in the constructor function. super allows the subclass to access properties that exist in the superclass. As the class tree grows in your code, it can be hard to keep track of your inheritance chain. Be wary of it!

I think I'll wrap this one up here. I may add a Part IV or not. Stay tuned!


Works Cited

Haverbeke, Martin "The Secret Life of Objects", Eloquent JavaScript - A Modern Introduction to Programming, 3rd Edition, 2019, Chapter 6, No Starch Press, Inc.

Top comments (0)