This is hopefully the first of a series of posts about object-oriented programming in JavaScript. You can’t get far in JavaScript without learning about functions and the built-in object types, but the mechanisms for defining your own object types aren’t quite as obvious. Let’s start as simple as we can – we’ll create an object that represents a two-dimensional point:
var pt = {};
pt.X = 3;
pt.Y = 4;
No surprises there. The pt object has two properties, X and Y. We can write functions that manipulate points; for example:
function MovePoint(pt, dx, dy)
{
pt.X += dx;
pt.Y += dy;
}MovePoint(pt, 1, 2);
Of course, we’d rather have a Move method on the pt object itself.
pt.Move = function (dx, dy) { this.X += dx; this.Y += dy; };pt.Move(1, 2);
When a function is assigned to a property of an object, and that function is called using the syntax shown, the special this variable references that object, so that when pt.Move is called, this.X refers to the X property of pt.
Now, it would be rather inconvenient to type all of that every time we need a new point, so we can write a function that creates a point.
function CreatePoint(x, y)
{
return { X : x, Y : y, Move : Point_Move };
}function Point_Move(dx, dy)
{
this.X += dx;
this.Y += dy;
}var pt = CreatePoint(3, 4);
pt.Move(1, 2);
I’ve also taken the liberty of creating a Point_Move function so that a new anonymous function isn’t created every time a new point is created. (The actual name of the Point_Move function isn’t relevant; I could have called it Krebf, but the Point_Move naming convention helps me remember that I’m using it as the Move method for a Point.)
This actually works quite well, but it would be more natural if we could use the new operator, as with built-in objects. Fortunately, this is easy enough to do – we just create a function that will serve as the constructor.
function Point(x, y)
{
this.X = x;
this.Y = y;
this.Move = Point_Move;
}var pt = new Point (3, 4);
pt.Move(1, 2);
The two approaches do almost exactly the same thing; new Point creates a new object and immediately calls the Point function as if it were a member of the new object. There are subtle (and useful) differences that I’ll describe in my next post.