JavaScript面向对象:创建对象
1.初级创建对象
var oCar=new Object; oCar.color='red'; oCar.door=4; oCar.map=3; oCar.showColor=function () { // body... alert(this.color); } console.log(oCar);
缺点:需要创建多个Car实例
2.工厂函数创建对象
function showColor(){ alert(this.color) } function createCar(sColor,iDoors,iMpg) { var oTempCar=new Object; oTempCar.color=sColor; oTempCar.door=iDoors; oTempCar.mpg=iMpg; oTempCar.showColor=showColor; return oTempCar; } var oCar1=createCar('red',2,23); oCar1.showColor();
缺点:看起来不像是对象的方法
3.构造函数创建对象
function Car(sColors,iDoors,iMpg) { // body... this.color=sColors; this.iDoors=iDoors; this.iMpg=iMpg; this.showColor=function(){ alert(this.color); } } var oCar1=new Car('red',4,23); var oCar2=new Car('blue',5,24)
优点:内部不需要创建对象,this直接可以访问; 缺点:会重复生成函数
4.原型方式创建对象
function Car() { // body... } Car.prototype.color='red'; Car.prototype.doors=4; Car.prototype.mpg=23; Car.prototype.drivers=['wang','xia']; Car.prototype.showColor=function(){ alert(this.color); } var oCar1=new Car(); var oCar2=new Car(); oCar1.drivers.push('yun'); console.log(oCar2.drivers);
缺点:没有参数,属性指向对象,对象共享,Car1修改,Car2也会跟着修改
5.混合构造/原型方式
function Car(sColor,iDoor,iMpg) { this.color=sColor; this.doors=iDoor; 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',5,24); oCar1.drivers.push('yun'); console.log(oCar1.drivers); console.log(oCar2.drivers);
构造函数定义非函数属性;原型定义函数属性
6.动态原型方式
function Car(sColor,iDoor,iMpg){ this.color=sColor; this.door=iDoor; this.mpg=iMpg; this.driver=new Array('Mike','Sue'); if(typeof Car._initialized=="undefined"){ Car.prototype.showColor=function(){ alert(this.color); } } Car._initialized=true; }