Main Page

Hybrid factory paradigm

Car.prototype.showColor = function () {
Car._initialized = true;
The constructor is identical until the line that checks if
typeof Car._initialized
is equal to
. 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
. If the value is defined (when it’s true, its
is Boolean),
then the methods aren’t created again. Simply put, this method uses a flag (
) 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
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 () {
return oTempCar;
Unlike the classic paradigm, this paradigm uses the
keyword to make it seem like an actual con-
structor is being called:
var car = new Car();
Because the
operator is called within the
constructor, the second
operator (called outside
of the constructor) is essentially ignored. The object created inside the constructor is passed back into the
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).
Chapter 3
06_579088 ch03.qxd 3/28/05 11:36 AM Page 96

JavaScript EditorFree JavaScript Editor     Ajax Editor