javascript 03对象
1、对象类型
1)本地对象(object、function、string、boolean、number、array、date)
2)内置对象(global、math)
3)宿主对象
2、定义对象
1)工厂方式(创建对象,需返回值)
eg1function createCar(){//封装创建的car对象
var oCar=new Object;
oCar.color="red";
oCar.doors=4;
oCar.mpg=23;
oCar.showColor=function(){
alert(this.color);
}
return oCar;
}
var oCar1=createCar();
var oCar2=createCar();
eg2 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",2,25);
oCar1.showColor();
oCar2.showColor();
2)构造函数方式(不需返回值,第一个字母大写,用new及类名创建对象)
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",5,35);
3)原型方式
function Car(){}
Car.prototype.color="red";
Car.prototype.doors=4;
Car.prototype.mpg=23;
Car.prototype.showColor=function(){
alert(this.color);
}
var oCar1=new Car();
var oCar2=new Car();
4)混合构造函数/原型方式
function Car(sColor,iDoors,iMpg){
this.color=sColor;
this.doors=iDoors;
this.mpg=iMpg;
this.drivers=new Array("Mike","Sue");
}
Car.prototype.showColor=function(){
alert(this.color);
}
var oCar1=new Car("red",4,23);
var oCar2=new Car("blue",2,25);
oCar1.drivers.push("Matt");
alert(oCar1.drivers);
alert(oCar2.drivers);
5)动态原型
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;
}
}
6)混合工厂方式
function Car(){
var oTempCar=new object;
oTempCar.color="red";
oTempCar.doors=4;
oTempCar.mpg=23;
oTempCar.showColor=function(){
alert(this.color)
}
return oTempCar;
}
3、修改对象