【问题标题】:Polymorphism and deep inheritance in JSJS中的多态和深度继承
【发布时间】:2011-07-27 17:09:38
【问题描述】:

我正在使用 JS prototype inheritance pattern from Gavin Kistner,但我不太确定为什么深度继承对我不起作用。

我希望 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() 的无限调用循环...

我做错了什么?
我应该简单地将“init”重命名为 B 和 C 的其他名称吗?我宁愿不要,因为目前的方式允许我调用obj.init() obj 是A、B 还是C 类型...

【问题讨论】:

  • 这样的继承是错误的。像这样的经典 OO 不应该被入侵到 JavaScript 中。请改用原型 OO 和特征
  • @Raynos Raynos 是对的。 Raynos,您可以添加指向您喜欢的示例的链接吗?
  • TraitsJS 是一个很棒的原型 OO 库。只是限制自己只使用Object.create、Trait 并且只有一层深的原型继承链应该会产生良好的原型 OO
  • 这已经过时了一段时间,但与此同时,我学到了更多东西并同意 Raynos,感谢您的提醒!

标签: javascript inheritance polymorphism prototypejs hierarchy


【解决方案1】:

将B.parent.init.call( this, arg ); 更改为B.prototype.parent.init.call( this, arg );。

【讨论】:

  • 啊啊啊,这是我的问题。这是一个错字,这一行实际上是“this.prototype.parent.init.call(this, arg)”。我将其更改为使用类名而不是“this”,并按照您的建议添加了“.prototype”,效果很好!谢谢!!
【解决方案2】:

这并不能回答你的问题,但我最近一直在做一些关于 JavaScript 继承的工作。如果你想走经典路线,我真的可以推荐JS.Class;这是一个让课程变得非常简单的库。

如果可以,你应该避免使用这个库,但如果你不想处理 JavaScript 继承/原型设计的头痛,我可以推荐 JS.Class。

【讨论】:

  • 您确实应该避免所有经典的 OO 仿真。我还推荐 traitsJS 作为典型的 OO 替代方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-19
  • 2016-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多