Main Page

Hybrid factory paradigm

Car.prototype.showColor = function () {
alert(this.color);
};
Car._initialized = true;
}
}
The constructor is identical until the line that checks if
typeof Car._initialized
is equal to
“unde-
fined”
. This line is the most important part of the dynamic prototype method. If this value is unde-
fined, the constructor continues on to define the methods of the object using the prototype paradigm
and then sets
Car._initialized
to
true
. If the value is defined (when it’s true, its
typeof
is Boolean),
then the methods aren’t created again. Simply put, this method uses a flag (
_initialized
) to deter-
mine if the prototype has been assigned any methods yet. The methods are only created and assigned
once, and to the delight of traditional OOP developers, the code looks more like class definitions in other
languages.
Hybrid factory paradigm
This paradigm is typically used as a workaround when the previous paradigms don’t work. Here, the
aim is to create a dummy constructor that simply returns a new instance of another type of object. The
code looks very similar to the class paradigm’s factory function:
function Car() {
var oTempCar = new Object;
oTempCar.color = “red”;
oTempCar.doors = 4;
oTempCar.mpg = 23;
oTempCar.showColor = function () {
alert(this.color)
};
return oTempCar;
}
Unlike the classic paradigm, this paradigm uses the
new
keyword to make it seem like an actual con-
structor is being called:
var car = new Car();
Because the
new
operator is called within the
Car()
constructor, the second
new
operator (called outside
of the constructor) is essentially ignored. The object created inside the constructor is passed back into the
variable
car
.
This paradigm has the same problems as the classic paradigm regarding memory management of object
methods. It is highly recommended that you avoid using this method unless absolutely necessary (see
Chapter 15, “XML in JavaScript,” for an example of such a case).
96
Chapter 3
06_579088 ch03.qxd 3/28/05 11:36 AM Page 96


JavaScript EditorFree JavaScript Editor     Ajax Editor


©