Main Page

Defining Classes and Objects

In this code, the function
showColor()
is defined first (using
this
). Then, two objects (
oCar1
and
oCar2
) are created, one with a
color
property set to
“red”
, and the other with a
color
property set
to
“blue”
. Both objects are assigned a property called
showColor
that points to the original function
named
showColor()
(note that no naming problem exists because one is a global function and the other
is a property of an object). When calling
showColor()
on each object, the
oCar1
outputs
“red”
whereas
oCar2
outputs
“blue”
. This happens because the this keyword in the function is equal to
car1
when
oCar1.showColor()
is called and equal to
oCar2
when
oCar2.showColor()
is called.
Note that the
this
keyword
must
be used when referring to properties of an object. For instance,
showColor()
wouldn’t work if it were written like this:
function showColor() {
alert(color);
}
Whenever a variable is referenced without an object or
this
before it, ECMAScript thinks that it is a
local or global variable. This function then looks for a local or global variable named
color
, which it
won’t find. The result? The function displays
“null”
in the alert.
Defining Classes and Objects
The capability to use predefined objects is only one part of an object-oriented language. The true power
comes because you can create your own classes and objects for specific uses. As with many things in
ECMAScript, you can accomplish this in a variety of ways.
Factory paradigm
Because properties of an object can be defined dynamically after its creation, a lot of developers wrote
code similar to the following when JavaScript was first introduced:
var oCar = new Object;
oCar.color = “red”;
oCar.doors = 4;
oCar.mpg = 23;
oCar.showColor = function () {
alert(this.color);
};
In this code, an object is created named
car
. The object is then given several properties: Its color is red, it
has four doors, and it gets 23 miles per gallon. The last property is actually a pointer to a function, which
means the property is a method. After this code is executed, you can use an object called
car
. The prob-
lem is that you may need to create more than one instance of a car.
To solve the problem, developers created
factory functions
, which create and return an object of a specific
type. For example, a function called
createCar()
could be used to encapsulate the creation of the
car
object described previously:
90
Chapter 3
06_579088 ch03.qxd 3/28/05 11:36 AM Page 90


JavaScript EditorFree JavaScript Editor     Ajax Editor


©