I'm using the JS prototype inheritance pattern from Gavin Kistner and I'm not quite sure why deep inheritance doesn't work for me.
I want C inherits from B inherits from A...
Function.prototype.inheritsFrom = function( parentClassOrObject )
{
if ( parentClassOrObject.constructor == Function )
{
//Normal Inheritance
this.prototype = new parentClassOrObject;
this.prototype.constructor = this;
this.prototype.parent = parentClassOrObject.prototype;
}
else
{
//Pure Virtual Inheritance
this.prototype = parentClassOrObject;
this.prototype.constructor = this;
this.prototype.parent = parentClassOrObject;
}
return this;
}
function A() {
// ...
}
A.prototype.init = function( arg ) {
// ...
}
function B() {
A.apply( this, arguments ); // call super constructor
// ...
}
B.inheritsFrom( A );
B.prototype.init = function( arg ) {
B.parent.init.call( this, arg );
// ...
}
function C() {
B.apply( this, arguments ); // call super constructor
// ...
}
C.inheritsFrom( B );
C.prototype.init = function( arg ) {
this.parent.init.call( this, arg );
// ...
}
var foo = new C();
foo.init( 10 );
// Throws an exception: infinite call loop.
When I call foo.init(), I'm actually calling C.init()
Inside C.init() 'this' is of type C
-> this.parent.init.call( this, arg ) is actually calling B.init()
Inside B.init() 'this' is still of type C ( because of .call(this))
-> this.parent.init.call( this, arg ) is, again, calling B.init()
And therefore it goes into an infinite call loop on B.init() ...
What am I doing wrong ?
Should I simply rename 'init' to something else for B and C ? I would rather not, because the current way allows me to call obj.init() whether obj is of type A, B or C...
Object.create,Traitand only have prototypical inheritance chains one level deep should produce good prototypical OO