↑
Main Page
adding arguments
function createCar() {
var oTempCar = new Object;
oTempCar.color = “red”;
oTempCar.doors = 4;
oTempCar.mpg = 23;
oTempCar.showColor = function () {
alert(this.color)
};
return oTempCar;
}
var oCar1 = createCar();
var oCar2 = createCar();
Here, all the previous lines of code are contained within the
createCar()
function, including one extra
line, which returns the car (
oTempCar
) as the function value. When this function is called, it creates a
new
Object
and assigns all the properties necessary to replicate the car object described earlier. Using
this method, it is easy to create two (or more) versions of a car object (
oCar1
and
oCar2
) that have the
exact same properties. Of course, the
createCar()
function can also be modified to allow the passing in
of default values for the various properties instead of just assigning default values:
function createCar(sColor, iDoors, iMpg) {
var oTempCar = new Object;
oTempCar.color = sColor;
oTempCar.doors = iDoors;
oTempCar.mpg = iMpg;
oTempCar.showColor = function () {
alert(this.color)
};
return oTempCar;
}
var oCar1 = createCar(“red”, 4, 23);
var oCar1 = createCar(“blue”, 3, 25);
oCar1.showColor(); //outputs “red”
oCar2.showColor(); //outputs “blue”
By adding arguments to the
createCar()
function, it is possible to assign values to the color, doors,
and mpg properties of the car object being created. This leaves two objects with the same properties but
different values for those properties.
As ECMAScript became more formalized, however, this method of creating objects fell out of favor and
is typically frowned upon today. Part of the reason for this was semantic (it doesn’t look as appropriate
as using the
new
operator with a constructor), and part was functional. The functional problem has to do
with the creation of object methods using this paradigm. In the previous example, every time the
createCar()
function is called, a new function is created called
showColor()
, meaning that every
object has its own version of
showColor()
when, in reality, each object should share the same function.
91
Object Basics
06_579088 ch03.qxd 3/28/05 11:36 AM Page 91
Free JavaScript Editor
Ajax Editor
©
→