开发者

Polymorphism and deep inheritance in JS

开发者 https://www.devze.com 2023-03-23 02:45 出处:网络
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'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...


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号