javascript定义类或对象的四种方式

本文介绍了使用JavaScript创建构造函数的四种不同方法。通过这些方法可以实例化带有特定属性和方法的对象,如颜色、门数和里程等。同时展示了如何利用原型继承来优化构造函数,减少每次实例化时重复定义相同方法的问题。

/*

function createCar(sColor,iDoors,iMpg){

var oTempCar=new Object;

oTempCar.color=sColor;

oTempCar.doors=iDoors;

oTempCar.mpg=iMpg;

oTempCar.showColor=function(){

window.alert(this.color);

};

return oTempCar;

}

var oCar1=createCar("red",4,23);

var oCar2=createCar("blue",6,40);

oCar1.showColor();

oCar2.showColor();

*/

/*

function Car(sColor,iDoors,iMpg){

this.color=sColor;

this.doors=iDoors;

this.mpg=iMpg;

this.showColor=function(){

window.alert(this.color);

};

}

var oCar1=new Car("red",4,23);

var oCar2=new Car("blue",6,40);

oCar1.showColor();

oCar2.showColor();

*/

/*

function Car(sColor,iDoors,iMpg){

this.color=sColor;

this.doors=iDoors;

this.mpg=iMpg;

}

Car.prototype.showColor=function(){

window.alert(this.color);

};

var oCar1=new Car("red",4,23);

var oCar2=new Car("blue",6,40);

oCar1.showColor();

oCar2.showColor();

*/

/*

function Car(sColor,iDoors,iMpg){

this.color=sColor;

this.doors=iDoors;

this.mpg=iMpg;

if(typeof Car._initialized=="undefined"){

Car.prototype.showColor=function(){

window.alert(this.color);

};

Car._initialized=true;

}

}

var oCar1=new Car("red",4,23);

var oCar2=new Car("blue",6,40);

oCar1.showColor();

oCar2.showColor();

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值