1. Hybrid constructor/prototype
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” |
Advantage: it has the advantages of other methods, but has no disadvantages of other methods.
Deficiency: lack of encapsulation
2. Dynamic Prototype
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 ;}} |
Advantage: encapsulation is better than the previous method
In short, the above two methods are currently the most widely used. Try to use them to avoid unnecessary problems.