If you’ve been learning about JavaScript for a bit now, you’ve probably done some work with functions and objects. What if I told you that there was a way to make objects that have similar properties in a much more efficient way than creating each object individually, painstakingly making sure all the keys have the same names, the values are the right type, etc.?
There are actually a number of different ways to do so, such as by using factory functions and classes, but for now, in case you somehow missed the title, we’ll focus on classes.
You may be wondering how classes can help us manage data in real-life situations. In this article, I’ll be using the example of managing content in a library, but classes could also be used for managing personnel, tracking info about different branches or locations of a business (like a restaurant or a bank), for managing curriculum data at a university, & the list goes on.
Before we look at our example, you should be aware that we must first make a parent class (a.k.a. ‘superclass’) before we create instances of the class. Each instance of a class is an object that contains the properties, methods, getters, & setters of the parent class, but has unique property values, and may contain their own properties, methods, etc.: more on this in the next paragraph. Think of the parent class as the template for constructing instances, as it contains the properties, getters, methods (functions that can be called on instances of the class), and setters (if necessary) that each instance & subclass has access to.
Instances of a class may be slightly different than others in that they may contain unique properties or methods that were not established in the parent class. For cases like this, we should create a child class (a.k.a. ‘subclass’). These contain everything that the parent class contains, only we can add more properties, getters, methods, & setters if we need to, and these would all be unique to the child class. But enough theoretical talk, let’s get our hands theoretically dirty & look at our aforementioned library example.
For the sake of brevity, let’s imagine that we live in 1889 & we have only one type of medium in our library: books. In a more realistic situation, there would be things like movies & CDs, for which we would want to create subclasses for. No doubt these will all have some properties, getters, methods, and maybe some setters in common, so let’s create a parent class called ‘Media’ with all of these, before making a subclass for books:
Create Parent Class ‘Media’
Let’s break down what’s happening in the picture above (the numbers below correspond to the numbers in the comments above):
We declare a class with the
class
keyword, followed by the class name and a curly bracket. Class names must be capitalized & written in CamelCase.We establish the classes properties with the constructorkeyword. The property names are passed into parentheses. We then set the values of the properties to default values, or to whatever is passed into the constructor parentheses when we later create instances of this class. Notice we use the
this._
syntax.For each property, we have to establish a corresponding getter so we can later access the corresponding values of each instance of the class.
We create the methods for the class, along with any necessary setters. In this example, we have a method that allows us to add a rating of 1–5 for the instance of this class (library item). This new rating is stored inside an array. Then, we have a method which uses the array where all the ratings are stored to determine the average rating of the library item. Finally, we have a method that toggles the checkout status of the item. This method requires a setter, so we put that directly before the method is declared.
Create ‘Book’, a Subclass of the Superclass ‘Media’
Now, let’s create a child class for all the books in our library. Keep in mind that we’ll need to add the properties author
& pages
, which are unique to books & don’t exist in the parent class or in other child classes we may make later for other items.
Let’s go over what’s going on:
We give the subclass a name, which follows the
class
keyword. After the class name is declared, we use the keywordextends
to indicate the new class is a subclass of, in this case,Media
.We use the constructor to establish properties of the subclass. These properties have no default value, so the
isCheckedOut
&ratingsproperties
from the superclass are not included as part of the constructor for this subclass, sinceisCheckedOut
has a default value offalse
, &ratings
is initially set to an empty array. The propertytitle
from the superclass is included in the constructor, since it has no default value. This subclass inherits this property from the superclass if we enter keywordsuper
& puttitle
in parentheses behind it. Because of this, we don’t need to make a getter for it, since it inherits this property from the superclass.Since we added two new properties that are particular to this subclass,
author
&pages
, we need to make a getter for each.
Create an Instance of Subclass ‘Book’
Now it’s time to put our classes to use by creating an instance. Let’s create a book item, titled ‘How 2 Rap’ by Eminem that has, of all numbers, 666 pages:
Once an instance is created, it behaves like an object (it technically is one). We can call its getters on it & log those values to the console to make sure we set everything up correctly. We can also call the methods that we established in the super- and subclass, on it.
There you have it, a bit about JavaScript classes. There is some conflict on when you should use them, if at all, but I will let you get into those wars of words yourself, whether that be in a YouTube comment section, on StackOverflow, or elsewhere, maybe even in the comment section below.
As always, let me know if you learned something or if you have questions. If you see I could have done something better, do tell.
Happy coding!
MDN Documentation on JS Classes
Originally published on Medium for JavaScript in Plain English on July 12, 2022
Top comments (0)