2.3: extends
Last updated
Last updated
It looks daunting, but it will not take a long time to read. Please go read the mdn docs about .
It's important to start familiarizing yourself with this idea of inheritance in JavaScript. Even though JavaScript is different than other languages with its inheritance, we'll talk in a somewhat classical sense so that you can get an idea of what inheritance is on a fundamental level.
Let's consider the class and add this code to your extends.js
file:
So let's say we wanted to make a bunch of different types of users: Trial, Bronze, Admin. Each one of these will have different functions available, but we all want them to have some properties that are similar. We can do this by making a new class that inherits certain properties from another class. We call this parent and child class. It's referred to as inheritance. Another way you might hear it referenced is 'subclass'.
Let's create a subclass that extends
the parent class:
So, when we use the extends
keyword, we are doing something that we, again, call subclassing. This means that the TrialUser
class becomes a child of User
, and therefore inherits all of its functions and properties.
You should also note that TrialUser
has a trialEnding
method, something that User won't have. This means that a child class can have its own separate methods.
Let's test this out by making some objects:
This is called inheritance. We use extends
to indicate that we are creating a new class that will inherit the properties and functions of another class and take on properties of its own. Fairly simple concept.
Go practice: Make a class called BannedUser. Write a method/function that tells the reason that prints out a message about why they have been banned.