1、工厂方式
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();
oCar1.showColor();//red
oCar2.showColor();//red
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,25);
var oCar2=createCar("blue",4,23);
oCar1.showColor();//red
oCar2.showColor();//blue
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,12);
var oCar2=createCar("blue",4,23);
oCar1.showColor();//red
oCar2.showColor();//blue
2、构造函数方式
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,45);
var oCar2=new Car("blue",4,34);
oCar1.showColor();//red
oCar2.showColor();//blue
3、原型方式
function Car(){
}
Car.prototype.color="red";
Car.prototype.doors=4;
Car.prototype.mpg=23;
Car.prototype.showColor=function(){
alert(this.color);//if this replaced by Car,output undefined
};
var oCar1=new Car();
var oCar2=new Car();
oCar1.showColor();//red
oCar2.showColor();//red
alert(oCar1 instanceof Car);//true
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);//if replaced by Car,output undefined
};
var oCar1=new Car();
var oCar2=new Car();
oCar1.drivers.push("vivi");
alert(oCar1.drivers);//Mike,Sue,vivi
alert(oCar2.drivers);//Mike,Sue,vivi
4、混合的构造函数原型方式
function Car(sColor,iDoors,iMpg){
this.color=sColor;
this.doors=iDoors;
this.mpg=iMpg;
this.drivers=new Array("Minke","susan");
}
Car.prototype.showColor=function(){
alert(this.color);
};
var oCar1=new Car("red",4,45);
var oCar2=new Car("blue",4,12);
oCar1.showColor();//red
oCar2.showColor();//blue
oCar1.drivers.push("mingming");
alert(oCar1.drivers);//Minke,susan,mingming
alert(oCar2.drivers);//Minke,susan
5、动态原型方法
function Car(sColor,iDoors,iMpg){
this.color=sColor;
this.doors=iDoors;
this.mpg=iMpg;
if(typeof Car._intialize=="undefined"){
Car.prototype.showColor=function(){
alert(this.color);
};
}
Car._initialized=true;
}
var oCar1=new Car("red",4,23);
var oCar2=new Car("blue",4,25);
oCar1.showColor();//red
oCar2.showColor();//blue
6、混合工厂方式
创建方式与工厂方式很相似,不过使用new实例化对象。一般情况下,应该避免使用这种方式。
一般使用构造函数原型方式定义类,即用构造函数定义对象的所有非函数属性,用原型方式定义对象的函数属性。结果所有函数只创建一次,而每个对象都有自己的对象属性实例。