【发布时间】: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