学习笔记:javascript定义类的过程(类一词是形象说法,javascript中并没有类一词)

Code
<script language="javascript">
//----------------定义一个对象---------------------------
var oCar=new Object();
oCar.color
="red";
oCar.doors
=4;
oCar.mpg
=23;
oCar.showColor
=function()
{
 alert(
this.color);
}
oCar.showColor();
//------如果定义具有相同属性和方法的多个对象(想到要封装上面这段代码形成类机制,使重用)-----------
function createCar(sColor,iDoors,iMpg)
{
 
var oCar=new Object();
 oCar.color
=sColor;
 oCar.doors
=iDoors;
 oCar.mpg
=iMpg;
 oCar.showColor
=function()
 {
  alert(
this.color); 
 }
 
return oCar;
}
var oCar1=createCar("red",4,23);
var oCar2=createCar("blue",4,23);
oCar1.showColor();
oCar2.showColor();
//--这样似乎实现了给一个类创建多个实例,但showColor这个方法的函数确在重复创建,制造了很多复本,因此想到把它封装到一个函数中----
function showColor()
{
 alert(
this.color); 
}
function createCar(sColor,iDoors,iMpg)
{
 
var oCar=new Object();
 oCar.color
=sColor;
 oCar.doors
=iDoors;
 oCar.mpg
=iMpg;
 oCar.showColor
=showColor;
 
return oCar;
}
var oCar1=createCar("red",4,23);
var oCar2=createCar("blue",4,23);
oCar1.showColor();
oCar2.showColor();
//----------有了this这个关键字,可以将上面代码继续简化,于是有了构造函数---------------------------
function showColor()
{
 alert(
this.color); 
}
function Car(sColor,iDoors,iMpg)
{
 
this.color=sColor;
 
this.doors=iDoors;
 
this.mpg=iMpg;
 
this.showColor=showColor;
}
var oCar1=new Car("red",4,23);
var oCar2=new Car("blue",4,23);
oCar1.showColor();
oCar2.showColor();
//------------已经正确了,但是showColor在外面怎么看都不是类Car的成员,于是引入原型prototype-----
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();
oCar1.showColor();
oCar2.showColor();
alert(oCar1 
instanceof(Car));//检查类型
//
---------------上面这段代码的构造函数不能带参数,肯定还得改造,于是采用构造函数和原型结合的方式------------------------
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",4,23);
oCar1.drivers.push(
"lilf","matt");
alert(oCar1.drivers);
alert(oCar2.drivers);
//--------------再次优化代码,保证showColor方法只创建唯一一次------------------------
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;
}
var oCar1=new Car("red",4,23);
var oCar2=new Car("blue",4,23);
oCar1.drivers.push(
"lilf","matt");
alert(oCar1.drivers);
alert(oCar2.drivers);
//总结:一般定义一个类,使用最后两种方法,即构造函数与原型相结合的方法
</script>

你可能感兴趣的:(学习笔记:javascript定义类的过程(类一词是形象说法,javascript中并没有类一词))