Polymorphism and deep inheritance in JS
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()
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 callobj.init()
whether obj is of type A, B or C...Change B.parent.init.call( this, arg );
to B.prototype.parent.init.call( this, arg );
.
This doesn't answer your question, but I have been doing some work with JavaScript inheritance recently. If you want to go the classical route, I can really recommend JS.Class; it's a library that makes classes really easy.
If you can, you should avoid using the library, but if you don't want to deal with the headache of JavaScript inheritance/prototyping, I can recommend JS.Class.
精彩评论