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”, 3 , 25 );
oCar1.drivers.push(“Matt”);
alert(oCar1.drivers); // outputs “Mike,Sue,Matt”
alert(oCar2.drivers); // outputs “Mike,Sue”
优点:具有其它方式的优点而没有其它方式的缺点
不足:封装性欠缺
2 . 动态原型方式
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 ;
}
}
优点:封装性比上一个方式更好
总之,以上2种方式是目前最广泛使用的,尽量使用它们避免不必要的问题。