《JavaScript高級程序設(shè)計》閱讀筆記(十三):定義類或?qū)ο?/span>
工廠方式
創(chuàng)建并返回特定類型的對象。
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)用示例:
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ù)方式
示例:
function Car(sColor,iDoors,iMpg){
this.color=sColor;
this.door=iDoors;
this.mpg=iMpg;
this.showColor=function(){
alert(this.color);
}
}
調(diào)用示例:
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 屬性,重寫前面的例子,代碼如下:
function Car(){
}
Car.prototype.color="red";
Car.prototype.doors=4;
Car.prototype.mpg=23;
Car.prototype.showColor=function(){
alert(this.color);
}
調(diào)用:
var oCar1=new Car();
var oCar2=new Car();
缺點:不能通過給構(gòu)造函數(shù)傳遞參數(shù)初始化屬性的值
混合的構(gòu)造函數(shù)/原型方式
聯(lián)合使用構(gòu)造函數(shù)和原型方式,示例如下:
function Car(sColor,iDoors,iMpg){
this.color=sColor;
this.door=iDoors;
this.mpg=iMpg;
}
Car.prototype.showColor=function(){
alert(this.color);
}
調(diào)用示例:
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)原型方法:
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
本文首發(fā)博客園,版權(quán)歸作者跟博客園共有。轉(zhuǎn)載必須保留本段聲明,并在頁面顯著位置給出本文鏈接,否則保留追究法律責(zé)任的權(quán)利。
浙公網(wǎng)安備 33010602011771號