Professor: Th at’s exactly what it is. I will now show you how to define your own
class.
Mike: But no complex numbers, please.
Professor: OK, let me think of something really simple. Are you familiar with ele-
mentary algebraic operations on two-dimensional vectors?
Maria: Can you please just briefly review the basics?
Professor: OK, let’s take vector addition a nd dot product. A ssume you h ave two
vectors, v
1
= (x
1
, y
1
) and v
2
= (x
2
, y
2
). You compute the sum of two vectors by
simply adding the corresp onding components, so that the x component of the resulting
vector is the sum of the x comp onents of both vectors, and the y componen t of the
resulting vector is the sum of the y components of both vectors:
v
1
+ v
2
= (x
1
+ x
2
, y
1
+ y
2
)
The dot product is the sum of the pro ducts of the corresponding compon ents of eac h
vector:
v
1
· v
2
= (x
1
x
2
+ y
1
y
2
)
Notice that the sum of two vectors is again a vector while the dot product of two
vectors is a single number.
We are going to define a class Vector, for which we first need a constructor. When-
ever y ou invoke a constructor using new, an object instance is automatically crea te d.
You d on’t need to worry about creating one by yourself. A constructor only needs to
set the initial state of the created object in stance b y settin g values o f its pro perties.
You can set those values using the th is keyword, which ac ts as a reference to the
object instance just being created. Here’s how a de finition of a Vector constructor
looks:
var Vector = function(x, y) {
//Create and initialize the properties x and y of the created
//instance of class Vector.
this.x = x;
this.y = y;
};
Notice that I capitalized th e name of the constructo r. Because constructors define
classes, it is a com mon convention that th ey have names that begin with capital letters.
In co ntrast, regular functions and variable names begin with lower-case letters.
When the body of a constructor starts to execute, a new object instance ha s already
been c reated and this is a reference to that obje ct instance. With the two assignment
statements inside the Vecto r() constructor, we created the properties x and y and
210 Meeting 11. Building Your Own Objects