Extend

by southerd

JavaScript

function extend(parent, child) {
    function F() {};
    F.prototype = parent.prototype;
    child.prototype = new F();
    child.prototype.constructor = child;
};

function Thing(number) { this.number = number }
Thing.prototype.name = function() {return "Thing" + this.number;};
Thing.prototype.doMischief = function() { console.log(this.name() + " did mischief!"); };

function Thing1() { Thing.call(this, 1); }
extend(Thing, Thing1);

function Cat(letter) { Thing.call(this, letter); }
extend(Thing, Cat);
Cat.prototype.name = function(){return "Cat" + this.number;};

function CatZ() { Cat.call(this, 'Z'); }
extend(Cat, CatZ);
CatZ.prototype.doMischief = function() {console.log(this.name() + " cleaned up mischief."); };

var t1 = new Thing1();
t1.doMischief();

var catA = new Cat('A');
catA.doMischief();

var catZ = new CatZ();
catZ.doMischief();

//Thing1 did mischief!
//CatA did mischief!
//CatZ cleaned up mischief.