Friday, January 2, 2015

Javascript prototypical inheritance by example

// Util.inherits - straight from node js sourcecode
var util = {
inherits: function (ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}
};

var Other = function () {

};

Other.prototype.stuff = function () {
console.log('Other!');
}

// create our Base constructor
var Base = function (a) {
this.a = a;
this.other = new Other();
};

// add a prototype method
Base.prototype.add = function () {
this.a++;
};

Base.prototype.callStuff = function () {
this.other.stuff();
}

/* ... */

// An ancestor of Base constructor
var ChildBase = function (b) {
// we have to invoke the Base consturctor with the current context.
Base.apply(this, arguments);

this.b = b;
};
// here is where inheritance happens
util.inherits(ChildBase, Base);

/* ... */

ChildBase.prototype.callOther = function () {
this.callStuff();
};

// instantiation
var childBase = new ChildBase(2);
// JS keyword instanceof works
console.log(childBase instanceof ChildBase); // true
console.log(childBase instanceof Base); // true
childBase.add();
console.log(childBase.a); // value will be 3
console.log(childBase.b); // value will be 2
childBase.callOther() // 'Other!'