↑
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() {
alert(this.color);
}
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
showColor()
function is defined before the
createCar()
function. Inside
createCar()
, the object is assigned a pointer to the already existing
showColor()
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 () {
alert(this.color)
};
}
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
this
keyword is used. When a constructor is called with the
new
operator, an object is created before the first
line of the constructor is executed; that object is accessible (at that point) only by using
this
. It is then
possible to assign properties directly to
this
that are returned as the function value by default (no need
to explicitly use the
return
operator).
92
Chapter 3
06_579088 ch03.qxd 3/28/05 11:36 AM Page 92
Free JavaScript Editor
Ajax Editor
©
→