JavaScript中定义类或对象有多种方法:
以创建Car为实例说明。
var oCar = new Object;
oCar.color ="red";
oCar.doors = 4;
oCar.mpg=23;
oCar.showColor = function()
{
alert(this.color);
}
function createCar(sColor,iDoors,iMpg)
{
var oTempCar = new Object;
oTempCar.color = sColor;
oTempCar.doors=iDoors;
oTempCar.mpg=iMpg;
oTempCar.showColor = function()
{
al(this.color)
}
return oTempCar;
}
弊端:每个对象都有自己的一个showColor函数。
构造函数方式:
function Car(sColor,iDoors,iMpg)
{
this.color= sColor;
this.doors = i;
this.mpg = iMpg;
this.showColor = function()
{
alert(this.color)
};
}
弊端:构造函数重复生成函数,可以用外部函数重写构造函数(不太懂);
function Car()
{
}
Car.prototype.color = "red";
Car.prototype.doors =4;
Car.prototype.mpg = 23;
Car.prototype.drivers = new Array("Mike","Sue");
Car.prototype.showColor = function()
{
alert(this.color);
}
弊端:给一个实例添加drivers,另一个实例也添加了。
function Car()
{
}
Car.prototype.color = "red";
Car.prototype.doors =4;
Car.prototype.mpg = 23;
Car.prototype.drivers = new Array("Mike","Sue");
Car.prototype.showColor = function()
{
alert(this.color);
}
解决了两种弊端。
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")
{
Car.prototype.showColor = function()
{
alert(this.color)
}
car._initialized = true;
}
}
function Car()
{
var oTempCar = new Object;
oTempCar.color="red";
oTempCar.doors = 4;
oTempCar.mpg = 23;
oTempCar.showColor = function()
{
ale(this.color)
}
return oTempCar;
}
采用哪种方式:
目前流行的是构造函数、原型方式,此外动态原型方式较为流行。