Javascript JS中的多态性与深度继承

Javascript JS中的多态性与深度继承,javascript,inheritance,polymorphism,prototypejs,hierarchy,Javascript,Inheritance,Polymorphism,Prototypejs,Hierarchy,我正在使用JS,我不太清楚为什么深层继承不适合我 我希望C继承B继承A Function.prototype.inheritsFrom = function( parentClassOrObject ) { if ( parentClassOrObject.constructor == Function ) { //Normal Inheritance this.prototype = new parentClassOrObject; this.p

我正在使用JS,我不太清楚为什么深层继承不适合我

我希望C继承B继承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.
当我调用
foo.init()
时,我实际上是在调用
C.init()

C.init()内部,“this”是类型C
->
this.parent.init.call(this,arg)
实际上正在调用
B.init()
在
B.init()
“this”仍然是C类型(因为
.call(this)

->
this.parent.init.call(this,arg)
再次调用
B.init()

因此它在
B.init()上进入无限调用循环

我做错了什么?

对于B和C,我是否应该简单地将“init”重命名为其他名称?我宁愿不这样做,因为当前的方式允许我调用
obj.init()
obj是类型A、B还是C…

更改
B.parent.init.call(这个,arg)
to
B.prototype.parent.init.call(this,arg)

这并不能回答您的问题,但我最近一直在做一些JavaScript继承方面的工作。如果你想走古典路线,我真的可以向你推荐;这是一个使课程变得非常简单的库


如果可以,您应该避免使用该库,但是如果您不想处理JavaScript继承/原型设计的麻烦,我可以推荐JS.Class。

aaaaaah请看,这是我的问题。这是一个输入错误,这一行实际上是“this.prototype.parent.init.call(this,arg)”。我将它改为使用类名而不是“this”,并按照您的建议添加了“.prototype”,它工作得非常好!谢谢像这样的继承是错误的。像这样的经典OO不应该被侵入JavaScript。请使用原型OO和特性instead@Raynos雷诺斯是对的。Raynos,你能添加一个你喜欢的例子的链接吗?是一个很好的原型OO库。仅仅限制自己只使用
对象。创建
特征
,并且只有一个层次的原型继承链应该会产生好的原型OO。这已经过时了一段时间,但在此期间,我学到了更多,并同意了Raynos的观点,感谢大家的提醒!您确实应该避免所有经典的OO模拟。我还建议将其作为典型的OO替代方案