This reading focuses on how to create classes in JavaScript.
Specifically, we're preparing to build the following inheritance hierarchy:
Animal
/ \
Cat Bird
/ \ \
HouseCat Tiger Parrot
There are 2 keywords that are essential for OOP with classes in JS.
These keywords are extends
and super
The extends keyword allows one to inherit from an existing class.
Based on the above hierarchy, you can code the Animal class like so:
class Animal {
// ... class code here ...
}
This is how the extends
keyword is used to setup inheritance relationships.
The super
keyword allows one to "borrow" functionality from a super-class, in a sub-class.
Before you begin, you need to think about things like:
What should go into the base class of Animal?
In other words, What will all the sub-classes inherit from the base class? What re the specific properties and methods that separate each class from others?
Generally, How will my classes relate to one another?
The plan can be as follows:
-
The
Animal
class constructor will have two properties:color
andenergy
-
The
Animal
class prototype will have 3 methods:isActive(), sleep()
andgetColor()
-
The
isActive()
method, wherever ran, will lower the value ofenergy
until it hits0
. TheisActive()
method will also report the updated value ofenergy
. Ifenergy
is at zero, the animal object will immediately go to sleep, by invoking thesleep()
method based on said condition -
The
getColor()
method will just console log the value in the color property. -
The
Cat
class will inherit fromAnimal
, with the additional sound,canJumpHigh
, andcanClimbTrees
properties specific to theCat
class. It will also have its ownmakeSound()
method. -
The
Bird
class will also inherit fromAnimal
, but is own specific properties will be quite different from Cat. Namely, the Bird class will have thesound
and thecanFly
properties, and themakeSound
method too. -
The
HouseCat
class will extend theCat
class, and it will have its ownhouseCatSound
as its special property. Additionally, it will override themakeSound()
method from theCat
class, but it will do so in an interesting way. If themakeSound()
method, on invocation, receives a single option argument - set to true, then it will run super.makeSound()
- in other words, run the code from the parent class (Cat) with the addition of running theconsole.log(this.houseCatSound)
. Effectively, this means that themakeSound()
method on theHouseCat
class' instance object will have two separate behaviors, based on whether we pass it true or false. -
The
Tiger
class will also inherit fromCat
, and it will come with its owntigerSound
property, while the rest of the behavior will be pretty much the same as in theHouseCat
class. -
Finally, the
Parrot
class will extend theBird
class, with its owncanTalk
property, and its ownmakeSound()
method, working with two conditionals: one that checks if the value of true was passed tomakeSound
during invocation, and another that checks the value stored insidethis.canTalk
property.