Objects: An example

The easiest way to learn about objects is by creating one. In this example, we will use an analogy that models a real-life phenomenon to demonstrate objects.

Sometime later this year, I am expecting a baby object. Although I currently have no instantiated baby objects in my life, I know that all baby objects have certain baby methods associated with them. For example, baby objects will always have a cry method, and an eat method as well.

Baby objects also have properties, some of which are known to us, some of which are not. The baby object will have eyes, but we don't know what colour they will be. For the sake of simplicity, let's play God for a moment, and pretend that we can make the baby with any properties we want. But first, we have to define the baby methods:

function cry()
{
document.writeln("<p>");
for(x=0; x<5; x++)
document.writeln("<br>WAAAAH! ");
}

function eat()
{
document.writeln("<p>(slurp, slobber, dribble - generally make a mess of things)");
}

This is where the JavaScript object model becomes somewhat convoluted. To make a 'class' in JavaScript, you have to define it as a function. In a true object-oriented language, a class defines the properties and methods that an object will have, like a blueprint. However, like a blueprint for a car, you can't do anything with the description - you have to make instances of the class (or instantiate it). When you instantiate a car (manufacture it), you then choose the specific properties that the car object has, such as colour, airconditioning, and so on.

For our baby object, we will create four properties: sex, hair, eyes and name. Defining these properties inside the baby class would look like this:

function Baby()
{
this.sex = "Male";
this.hair = "Brown";
this.eyes = "Hazel";
this.name = "Trav Jr";
}

Notice that unlike other functions, the Baby() function doesn't seem to do anything. The Baby() function is used to define baby objects - in this case, a baby object has four properties (or variables) associated with it. Every baby object that is created will contain these properties. If we want to make a baby, we simply use the new keyword to create a new baby:

var b1 = new Baby();

This will create a baby object with a sex property set to Male, a hair property set to Brown, the eyes property set to Hazel, and the name property set to Trav Jr. Notice that in the Baby() function, we used the 'this' keyword. The 'this' keyword is used in JavaScript to refer to the current object. In this example, the current object is the Baby() function, so the variables are bound to the baby function. We can now access the properties of the baby object using the dot (.) operator, as we would with any of JavaScript's properties. For example, if we wanted to alert the user to the b1 object's name, we would use the following code:

alert("B1's name is: " + b1.name);