Professor: Magnificent! I’m now even more excited about next week, when we’re
going to make your math worksheet generator interactive.1
11.2 JavaScript Objects Revisited
Professor: You already k now plenty about objects in JavaScript. You know that an
object is a composite value in the sense that it combines multiple values. It can in-
corporate either primitives or other objects, which act like its properties or members.
If a property is a function object, which you can invoke to do something, then such
a property is often called a method. You access an object’s properties by their names
using the property access operator in the form of either a dot or a pa ir of square brack-
ets. It is im portant that objec ts with the exception of strings are mutable. You also
know that JavaScript objects are manipulated by reference rather than by value, and
that you crea te an obje ct using the new operato r in com bination with an appropriate
constructo r.
That said, you can also create an object by means of an obje ct literal, which is simply a
comma-separated list of name and value pairs e nclosed within a pair of curly bra ckets.
A property name may either be a JavaScript identifier or a string literal, and must be
separated from its value by a colon (:). A value can be any JavaScript expression,
whose value—either primitive or object—becomes the value of the pro perty. Here’s
an example :
//An object with two properties representing a complex number
//1 + 3i:
var complex = {re: 1, im: 3};
//The conjugate of the above number:
var conjugate = {re: complex.re, im: -complex.im};
I created two objects, an object complex with the real part set to one and the im ag-
inary part set to three, and its conjugate. I used more com plicated expressions for
property values to construct the conjugate. You recall complex numbers from high
school algebra, don’t you?
Maria: Vag uely, but yes. Is this the square root of m inus one?
Professor: The square root of minus one is the imaginary unit i. A complex number
is composed of the real and imaginary parts and can be written as a + bi, where a is
the real part and b is the imaginary part. You get the conjugate of a complex number
simply by multiplying its imaginary par t by minus one.
1The math worksheet example continues on page 249.
11.2. JavaScript Objects Revisited 207