JS 創(chuàng)建類---混合的構(gòu)造函數(shù)/原型方式
prototype:原型.此對象的所有實例共享原型定義的數(shù)據(jù)和(對象)引用.一般用于防止重復(fù)創(chuàng)建函數(shù),浪費內(nèi)存.
原型中定義的所有函數(shù)和引用的對象都只創(chuàng)建一次;構(gòu)造函數(shù)中的方法則會隨著實例的創(chuàng)建重復(fù)創(chuàng)建(如果有對象或方法的話).
不管在原型中還是構(gòu)造函數(shù)中,屬性(值)都不共享.
創(chuàng)建類的最好方式是用構(gòu)造函數(shù)定義屬性,用原型定義方法。
這種方式同樣適用于繼承機制,用對象冒充繼承構(gòu)造函數(shù)的屬性,用原型鏈繼承 prototype 對象的方法。
//構(gòu)造函數(shù)
function Car(sColor,iDoors,iMpg) {
this.color = sColor; //定義屬性
this.doors = iDoors; //定義屬性
this.mpg = iMpg; //定義屬性
this.drivers = new Array("Mike","John");//定義數(shù)組對象.每個實例創(chuàng)建一個單獨的對象
}
//公共方法(共享),屬性不共享.
Car.prototype={
value:1, //屬性不共享
objs:new Array("A","B"), //對象共享引用
showColor : function() { //方法共享引用.
alert(this.color);
}
};
var oCar1 = new Car("red",4,23);
var oCar2 = new Car("blue",3,25);
oCar1.drivers.push("Bill"); //構(gòu)造方法中的對象都是各個獨立的.
oCar1.value=2; //屬性不共享.
oCar1.objs.push('C'); //原型中的對象都是共享引用的.
document.write(oCar1.drivers + "<br/>" );
//Mike1,John,Bill
oCar1.showColor(); //red
document.write(oCar2.objs + "<br/>" );
//A,B oCar1:A,B,C
document.write( "<br/>" +oCar2.value); //1
document.write( "<br/>" +oCar2.drivers); //Mike1,John
posted on 2012-08-03 16:50
紫蝶∏飛揚↗ 閱讀(986)
評論(0) 編輯 收藏 所屬分類:
div+css+js代碼