1
Dynamic properties are more correctly called accessor properties, which we’ll learn more about in
cal gear, which may be different.) In addition to the constructor—which is called
implicitly when we create a new object—we also created a method
shift
, which
allows us to change to a valid gear. Let’s see it in action:
const
car1
=
new
Car
(
"Tesla"
,
"Model S"
);
const
car2
=
new
Car
(
"Mazda"
,
"3i"
);
car1
.
shift
(
'D'
);
car2
.
shift
(
'R'
);
In this example, when we invoke
car1.shift('D')
,
this
is bound to
car1
. Similarly,
in
car2.shift('R')
, it’s bound to
car2
. We can verify that
car1
is in drive (D) and
car2
is in reverse (R):
>
car1
.
userGear
// "D"
>
car2
.
userGear
// "R"
Dynamic Properties
It may seem very clever that the
shift
method of our
Car
class prevents us from
inadvertently selecting an invalid gear. However, this protection is limited because
there’s nothing to stop you from setting it directly:
car1.userGear = 'X'
. Most OO
languages go to great lengths to provide mechanisms to protect against this kind of
abuse by allowing you to specify the access level of methods and properties. Java‐
Script has no such mechanism, which is a frequent criticism of the language.
Dynamic properties
can help mitigate this weakness. They have the semantics of a
property with the functionality of a method. Let’s modify our
Car
class to take advan‐
tage of that:
class
Car
{
constructor
(
make
,
model
) {
this
.
make
=
make
;
this
.
model
=
model
;
this
.
_userGears
=
[
'P'
,
'N'
,
'R'
,
'D'
];
this
.
_userGear
=
this
.
_userGears
[
0
];
}
get
userGear
() {
return
this
.
_userGear
; }
set
userGear
(
value
) {
if
(
this
.
_userGears
.
indexOf
(
value
)
<
0
)
throw
new
Error(
`Invalid gear:
${
value
}
`
);
this
.
_userGear
=
vaule
;
}
shift
(
gear
) {
this
.
userGear
=
gear
; }
}
Object-Oriented Programming | 151