The first new thing we see is the
extends
keyword; this syntax marks
Car
as a sub‐
class of
Vehicle
. The second thing that you haven’t seen before is the call to
super()
.
This is a special function in JavaScript that invokes the superclass’s constructor. This
is required for subclasses; you will get an error if you omit it.
Let’s see this example in action:
const
v
=
new
Vehicle
();
v
.
addPassenger
(
"Frank"
);
v
.
addPassenger
(
"Judy"
);
v
.
passengers
;
// ["Frank", "Judy"]
const
c
=
new
Car
();
c
.
addPassenger
(
"Alice"
);
c
.
addPassenger
(
"Cameron"
);
c
.
passengers
;
// ["Alice", "Cameron"]
v
.
deployAirbags
();
// error
c
.
deployAirbags
();
// "BWOOSH!"
Note that we can call
deployAirbags
on
c
, but not on
v
. In other words, inheritance
works only one way. Instances of the
Car
class can access all methods of the
Vehicle
class, but not the other way around.
Polymorphism
The intimidating word polymorphism is OO parlance for treating an instance as a
member of not only its own class, but also any superclasses. In many OO languages,
polymorphism is something special that OOP brings to the table. In JavaScript, which
is not typed, any object can be used anywhere (though that doesn’t guarantee correct
results), so in a way, JavaScript has the ultimate polymorphism.
Very often in JavaScript, the code you write employs some form of duck typing. This
technique comes from the expression “if it walks like a duck, and quacks like a
duck…it’s probably a duck.” To use our
Car
example, if you have an object that has a
deployAirbags
method, you might reasonably conclude that it’s an instance of
Car
.
That may or may not be true, but it’s a pretty strong hint.
JavaScript does provide the
instanceof
operator, which will tell you if an object is an
instance of a given class. It can be fooled, but as long as you leave the
prototype
and
__proto__
properties alone, it can be relied upon:
class
Motorcycle
extends
Vehicle
{}
const
c
=
new
Car
();
const
m
=
new
Motorcyle
();
c
instanceof
Car
;
// true
c
instanceof
Vehicle
;
// true
m
instanceof
Car
;
// false
m
instanceof
Motorcycle
;
// true
m
instanceof
Vehicle
;
// true
Object-Oriented Programming | 157