Sample Video Frame

Created by Zed A. Shaw Updated 2024-02-17 04:54:36
 

23: Inheritance

In the previous exercise you learned about the concept of a class. A class allows you to encapsulate an interface in a single type so that other code expecting that type can work correctly without having to know about your implementation. In theory you should be able to take any objects of the same class and use them in any code expecting objects of that class.

Inheritance takes the concept of a class and allows you to make other "similar" classes by way of extending them in a parent and child relationship. You take a class you want to change, extend it with your new functionality, and you can use it anywhere the original can be used. This has advantages in saving you from having to implement code that someone else already wrote, allows you to work with existing code, and gives you some assurances that it will keep working.

Code Reuse

The first advantage of inheritance is to allow you to base new classes on old classes by only writing code to describe what's new. You can extend a Guitar class with a new Telecaster class rather than write a whole new Guitar class just so you can get a Telecaster class:

class Guitar {
    play(note) {
        // code for playing
    }
}

class Telecaster extends Guitar {
    volume(level) {
        // code for volume
    }

    tone(level) {
        // code for tone
    }
}

In this example I don't need to worry about writing a new play function for my Telecaster class because I am extending Guitar and Guitar already has one. I just write what's different about my Telecaster, which is it has volume and tone knobs.

Previous Lesson Next Lesson

Register for Learn JavaScript the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.