Parasitic Combination Inheritance
by Ryan Morris
JavaScript
// this is essentially what Object.create() does
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
// sets up a new prototype & constructor for the childObject
function inheritPrototype(childObject, parentObject) {
var prototype = Object.create(parentObject.prototype);
prototype.constructor = childObject;
childObject.prototype = prototype;
}
function ParentObject(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
ParentObject.prototype.sayName = function () {
alert(this.name);
};
function ChildObject(name, age) {
ParentObject.call(this, name);
this.age = age;
}
inheritPrototype(ChildObject, ParentObject);
ChildObject.prototype.sayAge = function () {
alert(this.age);
};