js定义类,你会吗?

<html>
<body>
<script language="javascript">
//代码一
var oCar=new Object;
oCar.color="red";
oCar.doors=4;
oCar.mpg=23;

oCar.showColor=function(){
alert(this.color);
};


//代码二function factory
function createCar(){
var oCar=new Object;
oCar.color="green";
oCar.doors=4;
oCar.mpg=23;

oCar.showColor=function(){
alert(this.color);
}
return oCar;
}

var oCar1=createCar();
var oCar2=createCar();

//代码三,所有对象都共享一个方法,每个创建新对象,都要创建新函数,而事实是对象共享一个方法
function createCar(sColor,iDoors,iMpg){
var oTempCar=new Object;
oTempCar.color=sColor;
oTempCar.idoors=iDoors;
oTempCar.impg=iMpg;

oTempCar.showColor=function(){
alert(this.color);
}

return oTempCar;
}

var oCar1=createCar("red",2,3);
var oCar2=createCar("green",3,5);

//代码四:

function showColor(){
    alert(this.color)
}

function createCar(sColor,iDoors,iMpg){
var oTempCar=new Object;
oTempCar.color=sColor;
oTempCar.idoors=iDoors;
oTempCar.impg=iMpg;
oTempCar.showColor=showColor;

return oTempCar;
}

var oCar1=createCar("red",2,3);
var oCar2=createCar("green",3,5);

//代码五,使用混合的构造函数/原型方式来构造对象
function Car(sColor,iDoors,iMpg,){
this.color=sColor;
this.idoors=iDoors;
this.impg=iMpg;
this.drivers=new Array("Mike","Sussen");
}

Car.prototype.showColor=function(){
alert(this.color);
}

var oCar1=new Car("red",1,25);
var oCar2=new Car("green",2,23);


//代码六:动态原型方法
function Car(sColor,iDoors,iMpg,){
this.color=sColor;
this.idoors=iDoors;
this.impg=iMpg;
this.drivers=new Array("Mike","Sussen");

if(typeof Car._initialized=="undefined"){
Car.prototype.showColor(){
alert(this.color);
}

Car._initialized=true;
}
}

//这种是网友加上去的,好用不好用,主流不主流,自己看着弄吧。

var object = {
    name:"name",
    sex:"sex",
    age:12
}
</script>
<body>
</html>

你可能感兴趣的:(JavaScript,html,function,object)