0.4.4: Classes
Learning Objectives
Understand the motivation behind JavaScript classes and object-oriented programming (OOP)
Understand how to use JavaScript class syntax to create and use classes
Understand how class inheritance works, how to use
super
to call parent class constructor
Introduction
The following is an example of a JavaScript class that represents cars. For simplicity, these cars only travel 1 unit of distance per trip.
JavaScript classes are templates for entities we may wish to manipulate as a unit in our apps. Classes are part of a broader computer science concept called object-oriented programming, also known as OOP. Classes are optional in JavaScript but mandatory in languages such as Java.
Without classes
Without classes, we might store data in JavaScript Objects and manipulate them with helper functions.
To reduce redundancy in object creation, we could write a helper function like createCar
to generate our objects.
With classes
JavaScript classes encapsulate the entity properties (colour
and odometer
above), entity creation method (createCar
above) and any entity helper methods (drive
above) within a single unit, i.e. class. This helps us organise our code by thinking of a Car
as a single entity, instead of an entity spread across disparate objects and helper functions.
We can represent many common app entities as classes, for example users.
Naming convention: Classes are typically named with UpperCamelCase. Instances are typically named with lowerCamelCase.
Class inheritance
One of the most valuable features of OOP and classes is "inheritance". Inheritance allows classes to "inherit" properties and methods from one another by forming "parent-child" relationships. For example, if I wanted to create classes for Bicycle
and Car
vehicle types, both of which have a speed
property and the same calcTravelTime
method that depends on speed
, I can define how we store the speed
property and define the calcTravelTime
method in a parent class Vehicle
and have Bicycle
and Car
classes inherit from Vehicle
to avoid repeating code.
Notice we use the keyword
extends
to specify inheritance in JavaScriptNotice we use the keyword
super
in constructor methods of child classesBicycle
andCar
to call the constructor method of their parent,Vehicle
.
Try creating a local file class-example.js
with the above code and running it with node class-example.js
, playing around with its features to understand how classes work!