欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript高級程序設(shè)計 閱讀筆記(十三) js定義類或?qū)ο?/h1>
 更新時間:2012年08月14日 16:04:46   作者:  
js定義類或?qū)ο蟮慕榻B,需要的朋友可以參考下
工廠方式

  創(chuàng)建并返回特定類型的對象?! ?

復(fù)制代碼 代碼如下:

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;
}

  調(diào)用示例:
復(fù)制代碼 代碼如下:

var oCar1=createCar("red",4,23);
var oCar2=createCar("blue",3,25);
oCar1.showColor();
oCar2.showColor();

  缺點:方法重復(fù)創(chuàng)建了。如在上面的調(diào)用示例中,oCar1和oCar2均有自己的shoColor方法,但這個是可以共用的。

構(gòu)造函數(shù)方式

  示例:

復(fù)制代碼 代碼如下:

function Car(sColor,iDoors,iMpg){
this.color=sColor;
this.door=iDoors;
this.mpg=iMpg;
this.showColor=function(){
alert(this.color);
}
}

  調(diào)用示例:
復(fù)制代碼 代碼如下:

var oCar1=new Car("red",4,23);
var oCar2=new Car("blue",3,25);

  缺點:跟工廠方式一樣,方法重復(fù)創(chuàng)建了。

原型方式

  本方式利用了對象的 prototype 屬性,可把它看成創(chuàng)建新對象所依賴的原型。這里用空構(gòu)造函數(shù)來設(shè)置類名,然后所有的屬性和方法都被直接賦予 prototype 屬性,重寫前面的例子,代碼如下:

復(fù)制代碼 代碼如下:

function Car(){
}

Car.prototype.color="red";
Car.prototype.doors=4;
Car.prototype.mpg=23;
Car.prototype.showColor=function(){
alert(this.color);
}


  調(diào)用:
復(fù)制代碼 代碼如下:

var oCar1=new Car();
var oCar2=new Car();

  缺點:不能通過給構(gòu)造函數(shù)傳遞參數(shù)初始化屬性的值

混合的構(gòu)造函數(shù)/原型方式

  聯(lián)合使用構(gòu)造函數(shù)和原型方式,示例如下:

復(fù)制代碼 代碼如下:

function Car(sColor,iDoors,iMpg){
this.color=sColor;
this.door=iDoors;
this.mpg=iMpg;
}

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

  調(diào)用示例:
復(fù)制代碼 代碼如下:

var oCar1=new Car("red",4,23);
var oCar2=new Car("blue",3,25);

  優(yōu)點:無內(nèi)存浪費,創(chuàng)建方便。

  這種方式是ECMAScript采用的主要方式。

動態(tài)原型方法

  使用混合的構(gòu)造函數(shù)/原型方式把對象的方法放在了對象外面定義,讓人感覺不是那么面向?qū)ο?,沒有在視覺上進行很好的封裝,因此產(chǎn)生了動態(tài)原型方法:

復(fù)制代碼 代碼如下:

function Car(sColor,iDoors,iMpg){
this.color=sColor;
this.door=iDoors;
this.mpg=iMpg;
if(typeof Car._initialized=="undefined"){
Car.prototype.showColor=function(){
alert(this.color);
};
Car._initialized=true;
}
}

作者:Artwl
出處:http://artwl.cnblogs.com

相關(guān)文章

最新評論