Prototypial inheritance

by podlipensky

JavaScript

var A = function(){
    console.log('A ctor called');
    this.a = 5; //this is a reference to newly created object in case when function is a constructor
};
A.prototype = {
    b: 10    
};
function extend(subclass, superclass){
    var F = function(){};//empty object in prototype chain in order to avoid superclass instantiation
    F.prototype = superclass.prototype;//inherit behavior form superclass.prototype
    subclass.prototype = new F();//put instance of F into prototype chain
    subclass.prototype.constructor = subclass;//correct constructor reference
    subclass.super = superclass;//leave a reference to superclass, for it's ctor usage
}
var B = function(){
    console.log('B ctor called');
    B.super.apply(this, arguments);
    this.c = 15;
};
extend(B, A);
B.prototype.t = 20; //B.prototype already substitued so we're safe to extend

console.log('b instantiation');

var b = new B();
var a = new A();

console.log(b.t);
console.log(a.t);//as we use intermediate F() function in prototype chain, A.prototype is not polluted with t property