Main Page

Constructor paradigm

Some got around this problem by defining the object methods outside of the factory functions and then
pointing to them:
function showColor() {
function createCar(sColor, iDoors, iMpg) {
var oTempCar = new Object;
oTempCar.color = sColor;
oTempCar.doors = iDoors;
oTempCar.mpg = iMpg;
oTempCar.showColor = showColor;
return oTempCar;
var oCar1 = createCar(“red”, 4, 23);
var oCar2 = createCar(“blue”, 3, 25);
oCar1.showColor(); //outputs “red”
oCar2.showColor(); //outputs “blue”
In this rewritten code, the
function is defined before the
function. Inside
, the object is assigned a pointer to the already existing
function. Functionally,
this solves the problem of creating duplicate function objects; but semantically, the function doesn’t look
like it is a method of an object.
All these problems led to the creation of developer-defined constructors.
Constructor paradigm
Creating a constructor is just as easy as defining a factory function, if not easier. The first step is selection
of a class name, which becomes the name of the constructor. Traditionally, this name begins with a capi-
tal letter to differentiate it from variable names, which typically begin with lowercase letters. Other than
this difference, a constructor looks a lot like a factory function. Consider the following example:
function Car(sColor, iDoors, iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.showColor = function () {
var oCar1 = new Car(“red”, 4, 23);
var oCar2 = new Car(“blue”, 3, 25);
The first difference you may notice is that no object is created inside the constructor; instead, the
keyword is used. When a constructor is called with the
operator, an object is created before the first
line of the constructor is executed; that object is accessible (at that point) only by using
. It is then
possible to assign properties directly to
that are returned as the function value by default (no need
to explicitly use the
Chapter 3
06_579088 ch03.qxd 3/28/05 11:36 AM Page 92

JavaScript EditorFree JavaScript Editor     Ajax Editor