Main Page

Prototype paradigm

Creating the object is now much more like general object creation in ECMAScript by using the
new
oper-
ator with the class name
Car
. You may be wondering if this paradigm has the same problems as the
previous one with managing functions. The answer is yes.
Just like factory functions, constructors duplicate functions, effectively creating a separate copy of a
function for each object. Also similar to factory functions, constructors can be rewritten with external
functions, but again, semantically they don’t make sense. This is where the prototype paradigm becomes
advantageous.
Prototype paradigm
This paradigm makes use of an object’s
prototype
property, which is considered to be the prototype
upon which new objects of that type are created. Here, an empty constructor is used only to set up the
name of the class. Then, all properties and methods are assigned directly to the
prototype
property.
Rewriting the previous example, the code looks like this:
function Car() {
}
Car.prototype.color = “red”;
Car.prototype.doors = 4;
Car.prototype.mpg = 23;
Car.prototype.showColor = function () {
alert(this.color);
};
var oCar1 = new Car();
var oCar2 = new Car();
In this code, the constructor (
Car
) is defined first and contains no code. The next few lines of code define
the object’s properties by adding them to the
prototype
property of
Car
. When
new Car()
is called,
all the properties of prototype are immediately assigned to the object that was created, meaning that all
instances of
Car
contain pointers to the same
showColor()
function. Semantically, everything looks like
it belongs to an object, so the two problems of the previous paradigms have been solved. As an added
bonus, this method allows the use of the
instanceof
operator to check what kind of object a given vari-
able points to. So the following line outputs
true
:
alert(oCar1 instanceof Car); //outputs “true”
It seems like this is a great solution. Unfortunately, not everything is better here.
First, you may notice that the constructor has no arguments. When using the prototype paradigm, it is
impossible to set the initial values of properties by passing arguments to the constructor, so both
car1
and
car2
have
color
equal to
“red”
,
doors
equal to
4
, and
mpg
equal to
23
. This means any changes to
the default values must be done after the object is created, which is annoying — but not the end of the
world. The real problem arises when one of the properties points to an object other than a function.
Functions can be shared without any consequences, but objects are rarely meant to be shared across all
instances. Consider the following example:
function Car() {
}
93
Object Basics
06_579088 ch03.qxd 3/28/05 11:36 AM Page 93


JavaScript EditorFree JavaScript Editor     Ajax Editor


©