that name. When we replace
shift
with our own home-grown version, both
car1
and its prototype have a method of this name. When we invoke
car1.shift('d')
, we
are now invoking the method on
car1
, not its prototype.
Most of the time, you won’t have to understand the mechanics of the prototype chain
and dynamic dispatch, but every once in a while, you’ll run into a problem that will
require you to dig deeper—and then it’s good to know the details about what’s going
on.
Static Methods
So far, the methods we’ve considered are instance methods. That is, they are designed
to be useful against a specific instance. There are also static methods (or class meth‐
ods), which do not apply to a specific instance. In a static method,
this
is bound to
the class itself, but it’s generally considered best practice to use the name of the class
instead of
this
.
Static methods are used to perform generic tasks that are related to the class, but not
any specific instance. We’ll use the example of car VINs (vehicle identification num‐
bers). It doesn’t make sense for an individual car to be able to generate its own VIN:
what would stop a car from using the same VIN as another car? However, assigning a
VIN is an abstract concept that is related to the idea of cars in general; hence, it’s a
candidate to be a static method. Also, static methods are often used for methods that
operate on multiple vehicles. For example, we may wish to have a method called
are
Similar
that returns
true
if two cars have the same make and model and
areSame
if
two cars have the same VIN. Let’s see these static methods implemented for
Car
:
class
Car
{
static
getNextVin
() {
return
Car
.
nextVin
++
;
// we could also use this.nextVin++
// but referring to Car emphasizes
// that this is a static method
}
constructor
(
make
,
model
) {
this
.
make
=
make
;
this
.
model
=
model
;
this
.
vin
=
Car
.
getNextVin
();
}
static
areSimilar
(
car1
,
car2
) {
return
car1
.
make
===
car2
.
make
&&
car1
.
model
===
car2
.
model
;
}
static
areSame
(
car1
,
car2
) {
return
car1
.
vin
===
car2
.
vin
;
}
}
Car
.
nextVin
=
0
;
const
car1
=
new
Car
(
"Tesla"
,
"S"
);
Object-Oriented Programming | 155