↑
Main Page
Hybrid constructor/prototype paradigm
Car.prototype.color = “red”;
Car.prototype.doors = 4;
Car.prototype.mpg = 23;
Car.prototype.drivers = new Array(“Mike”, “Sue”);
Car.prototype.showColor = function () {
alert(this.color);
};
var oCar1 = new Car();
var oCar2 = new Car();
oCar1.drivers.push(“Matt”);
alert(oCar1.drivers); //outputs “Mike,Sue,Matt”
alert(oCar2.drivers); //outputs “Mike,Sue,Matt”
Here, a property called
drivers
is a pointer to an
Array
containing two names,
Mike
and
Sue
. Because
drivers
is a reference value, both instances of
Car
point to the same array. This means that when
“Matt”
is added to
car1.drivers
, it is also reflected in
car2.drivers
. Outputting either one of these
pointers results in the string
“Mike,Sue,Matt”
being displayed.
With so many problems in creating objects, you must be wondering if there is any way to create objects
in a rational way. The answer is to combine the best of both constructor and prototype paradigms.
Hybrid constructor/prototype paradigm
By using both the constructor and prototype paradigms, you can create an object just as you would
when using other programming languages. The concept is very simple: Use the constructor paradigm
to define all nonfunction properties of the object and use the prototype paradigm to define the function
properties (methods) of the object. The result is that functions are only created once, but each object can
have its own instance of object properties. If you once again rewrite this example, the code becomes the
following:
function Car(sColor, iDoors, iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array(“Mike”, “Sue”);
}
Car.prototype.showColor = function () {
alert(this.color);
};
var oCar1 = new Car(“red”, 4, 23);
var oCar2 = new Car(“blue”, 3, 25);
oCar1.drivers.push(“Matt”);
alert(oCar1.drivers); //outputs “Mike,Sue,Matt”
alert(oCar2.drivers); //outputs “Mike,Sue”
94
Chapter 3
06_579088 ch03.qxd 3/28/05 11:36 AM Page 94
Free JavaScript Editor
Ajax Editor
©
→