or with the
operator to perform string concatenation. If you don’t implement this
method, your class will inherit the default implementation from
will convert to the useless string “[object Object]”. A
method might return
a human-readable string suitable for display to end users of your program. Even if this
is not necessary, however, it is often useful to define
for ease of debugging.
The Range and Complex classes in Examples 9-2 and 9-3 have
do the enumerated types of Example 9-7. We’ll define a
method for the Set
class of Example 9-6 below.
is closely related to
: it should convert an object to a
string in a locale-sensitive way. By default, objects inherit a
that simply calls their
method. Some built-in types have useful
methods that actually return locale-dependent strings. If you find yourself
method that converts other objects to strings, you should also
method that performs those conversions by invoking the
method on the objects. We’ll do this for the Set class below.
The third method is
. Its job is to convert an object to a primitive value. The
method is invoked automatically when an object is used in a numeric context,
with arithmetic operators (other than
) and with the relational operators, for example.
Most objects do not have a reasonable primitive representation and do not define this
method. The enumerated types in Example 9-7 demonstrate a case in which the
method is important, however.
The fourth method is
, which is invoked automatically by
The JSON format is intended for serialization of data structures and can handle Java-
Script primitive values, arrays, and plain objects. It does not know about classes, and
when serializing an object, it ignores the object’s prototype and constructor. If you call
on a Range or Complex object, for example, it returns a string like
. If you pass these strings to
obtain a plain object with properties appropriate for Range and Complex objects, but
which do not inherit the Range and Complex methods.
This kind of serialization is appropriate for classes like Range and Complex, but for
other classes you may want to write a
method to define some other serializa-
tion format. If an object has a
does not serialize
the object but instead calls
and serializes the value (either primitive or object)
that it returns. Date objects, for example, have a
method that returns a string
representation of the date. The enumerated types of Example 9-7 do the same: their
method is the same as their
method. The closest JSON analog to
a set is an array, so we’ll define a
method below that converts a Set object to
an array of values.
The Set class of Example 9-6 does not define any of these methods. A set has no prim-
itive representation, so it doesn’t make sense to define a
method, but the
class should probably have
220 | Chapter 9: Classes and Modules