Parasitic Combination Inheritance
Considered the most optimal inheritance paradigm for reference types.
by Tyler Bellerose
JavaScript
var page = document.getElementById('page');
function inheritPrototype(subType, superType){
var prototype = Object(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
function SuperType(name) {
this.name = name;
this.colors = ['red', 'blue', 'green'];
if (typeof this.sayName != "function") {
SuperType.prototype.sayName = function() {
return this.name;
};
}
}
/*
SuperType.prototype.sayName = function() {
return this.name;
};*/
function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
if (typeof this.sayAge != "function") {
SubType.prototype.sayAge = function() {
return this.age;
}
}
}
inheritPrototype(SubType, SuperType);
/*SubType.prototype.sayAge = function() {
return this.age;
};*/
var instance = new SubType("Tyler", 30);
page.innerHTML += instance.sayName() + "<br>";
page.innerHTML += instance.sayAge() + "<br>";
instance.colors.push('black');
page.innerHTML += instance.colors + "<br>";
var instance2 = new SubType("Greg", 22);
page.innerHTML += instance2.sayName() + "<br>";
page.innerHTML += instance2.sayAge() + "<br>";
page.innerHTML += instance2.colors + "<br>";