Classical inheritance explained

by dsbonev

JavaScript

/* Classical inheritance */
function inherit(Subclass, Superclass) {
    //1)protects the Superclass' prototype from modification by hiding it behind proxy prototype
    var Proxytype = function () {}; 
    
    //2)share the Superclass prototype instead of making an instance object; prevents Superclass instance members to leak to Subclass after deleting a Subclass' one
    Proxytype.prototype = Superclass.prototype;
    
    //3)this makes the Subclasss' prototype a new object that could be safely modified because it is not shared between all Subclassses
    Subclass.prototype = new Proxytype();
    
    //4)save a reference to Superclass' prototype to be able to call it's members
    Subclass._superclass = Superclass.prototype;
    
    //5)
    Subclass.prototype.constructor = Subclass;
}

function Shape(name) {
    this.name = name;
    this.supertypeInstance = true;
}

Shape.prototype.getName = function () {
    return this.name + ((this._superclass && this._superclass.getName) ?  
                        ' ' + this._superclass.getName() : ' ');
}

function Circle(name) {
    this.name = name;
}
    
Circle.prototype.getName = function () {
    return this.name + ((this._superclass && this._superclass.getName) ?  
                        ' ' + this._superclass.getName() : ' ');
}

inherit(Circle, Shape);

Circle.prototype.subclassSharedProperty = true;

var mediumCircle = new Circle('medium');

//1) 3)
console.log('Subclass modified Superclass: ' + !!Shape.prototype.subclassSharedProperty);

//2)
console.log('Superclass instance member visible: ' + !!mediumCircle.supertypeInstance);

//4 
console.log(mediumCircle.getName());

//5
console.log(mediumCircle.constructor.name);
console.log(Object.getPrototypeOf(mediumCircle));