This example produces the same result as a
for...in
loop (and we don’t have to
check
hasOwnProperty
). It’s handy whenever you need the property keys of an object
as an array. For example, it makes it easy to list all the properties of an object that
start with the letter x:
const
o
=
{
apple
:
1
,
xochitl
:
2
,
balloon
:
3
,
guitar
:
4
,
xylophone
:
5
, };
Object
.
keys
(
o
)
.
filter
(
prop
=>
prop
.
match
(
/^x/
))
.
forEach
(
prop
=>
console.log(
`
${
prop
}
:
${
o
[
prop
]
}
`
));
Object-Oriented Programming
Object-oriented programming (OOP) is an old paradigm in computer science. Some
of the concepts we now know as OOP begin to appear in the 1950s, but it wasn’t until
the introduction of Simula 67 and then Smalltalk that a recognizable form of OOP
emerged.
The basic idea is simple and intuitive: an object is a logically related collection of data
and functionality. It’s designed to reflect our natural understanding of the world. A
car is an object that has data (make, model, number of doors, VIN, etc.) and func‐
tionality (accelerate, shift, open doors, turn on headlights, etc.). Furthermore, OOP
makes it possible to think about things abstractly (a car) and concretely (a specific
car).
Before we dive in, let’s cover the basic vocabulary of OOP. A class refers to a generic
thing (a car). An instance (or object instance) refers to a specific thing (a specific car,
such as “My Car”). A piece of functionality (accelerate) is called a method. A piece of
functionality that is related to the class, but doesn’t refer to a specific instance, is
called a class method (for example, “create new VIN” might be a class method: it
doesn’t yet refer to a specific new car, and certainly we don’t expect a specific car to
have the knowledge or ability to create a new, valid VIN). When an instance is first
created, its constructor runs. The constructor initializes the object instance.
OOP also gives us a framework for hierarchically categorizing classes. For example,
there could be a more generic vehicle class. A vehicle may have a range (the distance it
can go without refueling or recharging), but unlike a car, it might not have wheels (a
boat is an example of a vehicle that probably doesn’t have wheels). We say that vehicle
is a superclass of car, and that car is a subclass of vehicle. The vehicle class may have
multiple subclasses: cars, boats, planes, motorcycles, bicycles, and so on. And sub‐
classes may, in turn, have additional subclasses. For example, the boat subclass may
have further subclasses of sailboat, rowboat, canoe, tugboat, motorboat, and so on.
We’ll use the example of a car throughout this chapter, as it’s a real-world object we
can probably all relate to (even if we don’t participate in the car culture).
Object-Oriented Programming | 149