|
// Based on http://pivotallabs.com/javascript-constructors-prototypes-and-the-new-keyword/ |
|
// |
|
// Example of how to implement object oriented functionality using Javascript. |
|
// |
|
// The explicitly set value of wheelCount stays set as 4 even after the prototype value is changed. |
|
|
|
// Class definition / constructor |
|
var Vehicle = function Vehicle(wheels) { |
|
// Initialization |
|
if (wheels) { |
|
this.wheelCount = wheels; |
|
} |
|
}; |
|
|
|
// Instance methods |
|
Vehicle.prototype = { |
|
report: function report(msg) { |
|
console.log(msg + ";" + " Wheels: " + this.wheelCount); |
|
}, |
|
wheelCount: 2 |
|
}; |
|
|
|
//////////////////////////////////////////////// |
|
// Vehicle 1 |
|
var vehicle1 = new Vehicle(); |
|
vehicle1.report("vehicle1 initialized"); // "vehicle1 initialized; Wheels: 2" |
|
|
|
vehicle1.wheelCount = 4; |
|
vehicle1.report("set to 4"); // "set to 4; Wheels: 4" |
|
console.log("prototype value: " + Vehicle.prototype.wheelCount); // "prototype value: 2" |
|
|
|
Vehicle.prototype.wheelCount = 18; |
|
console.log("reset in prototype: " + Vehicle.prototype.wheelCount); // "reset in prototype: 18" |
|
vehicle1.report("value in object"); // "value in object; Wheels: 4" |
|
|
|
// Conclusion: The value in an object overrides the default value set in the prototype |
|
|
|
//////////////////////////////////////////////// |
|
// Vehicle 2 |
|
var vehicle2 = new Vehicle(); |
|
vehicle2.report("vehicle2 initialized"); // "vehicle2 initialized; Wheels: 18" |
|
|
|
Vehicle.prototype.wheelCount = 3; |
|
console.log("reset in prototype: " + Vehicle.prototype.wheelCount); // "reset in prototype: 3" |
|
vehicle2.report("value in object"); // "value in object; Wheels: 3" |
|
|
|
// Conclusion: An objects property that isn't set by the constructor still points to the prototypes value |
|
|
|
//////////////////////////////////////////////// |
|
// Vehicle 3 |
|
var vehicle3 = new Vehicle(99); |
|
vehicle3.report("vehicle3 initialized"); // "vehicle3 initialized; Wheels: 99" |
|
|
|
Vehicle.prototype.wheelCount = 3; |
|
console.log("reset in prototype: " + Vehicle.prototype.wheelCount); // "reset in prototype: 3" |
|
vehicle3.report("value in object"); // "value in object; Wheels: 99" |
|
|
|
// Conclusion: Changing the prototype value doesn't change the instance value still |
@dfkaye pointed out a bug with the last revision of my code above where the last example referred to vehicle2, not vehicle3