Main Page

Dynamic prototype method

Now that’s more like it. All the nonfunction properties are defined in the constructor, meaning that once
again it is possible to assign default values by passing arguments into the constructor. Only one instance
of the
function is being created, so there is no wasted memory. Additionally, when
to the
array, it has no effect on
’s array, so when it output these arrays,
. Because
the prototype paradigm is used, it is still possible to use the
operator to determine the type
of object.
In case you haven’t figured it out, this paradigm is the dominant form used in ECMAScript because it
combines the positive attributes of the other paradigms without any of the harsh side effects. However,
some developers feel this is still not enough.
Dynamic prototype method
For developers coming from other languages, using the hybrid constructor/prototype paradigm is a lit-
tle jarring. After all, most object-oriented languages provide some sort of visual encapsulation of proper-
ties and methods when defining classes. Consider the following Java class:
class Car {
public String color = “red”;
public int doors = 4;
public int mpg = 23;
public Car(String color, int doors, int mpg) {
this.color = color;
this.doors = doors;
this.mpg = mpg;
public void showColor() {
Java provides a nice wrap of all properties and methods of the
class, so the code really looks more
like what it does: It defines information for one object. Critics of the hybrid constructor/prototype
paradigm say that it isn’t logical to look for some properties inside of the constructor and others outside
of it. So, the dynamic prototype method was devised to provide a more friendly coding style.
The basic idea behind dynamic prototyping is the same as the hybrid constructor/prototype paradigm:
Nonfunction properties are defined in the constructor, whereas function properties are defined on the
prototype property. The one difference is where the assignment of the methods takes place. Take a look
at the
class rewritten using dynamic prototyping:
function Car(sColor, iDoors, iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array(“Mike”, “Sue”);
if (typeof Car._initialized == “undefined”) {
Object Basics
06_579088 ch03.qxd 3/28/05 11:36 AM Page 95

JavaScript EditorFree JavaScript Editor     Ajax Editor