【发布时间】:2011-07-09 03:39:46
【问题描述】:
当我在 JS 中进行继承时,我在派生类中发现与基类属性重复的额外属性;我猜不出如何强制派生类使用基类的属性。我需要在正确的方向上稍加推动,以便我可以修复我的继承模型,或者我可以改变我使用原型继承的方式。
假设我从这个典型的继承函数开始:
Function.prototype.inheritsFrom = function( parentClassOrObject ){
if ( parentClassOrObject.constructor == Function ) {
this.prototype = new parentClassOrObject; //Normal Inheritance
this.prototype.constructor = this;
this.prototype.parent = parentClassOrObject.prototype;
} else {
this.prototype = parentClassOrObject; //Pure Virtual Inheritance
this.prototype.constructor = this;
this.prototype.parent = parentClassOrObject;
}
return this;
};
你可能以前见过这个。现在我创建以下继承:
function base() {
this.id = 0;
};
base.prototype.init = function ( _id ){
this.id = _id;
};
function entity(){
};
entity.inheritsFrom( base );
entity.prototype.init = function( _id ){
this.parent.init.call( this, _id );
};
现在我们使用实体类如下:
var e = new entity();
e.init( "Mickey" );
console.log( e.id );
当我检查我的新实体类的属性时……我现在有两个 ID(见下面的输出)。显然这是一个微不足道的案例,但我花了很多时间试图让它发挥作用。
e: entity
id: "Mickey"
__proto__: base
constructor: function entity(){
id: 0
init: function ( _id ){
parent: base
__proto__: base
为什么我有两个 ID?派生类甚至不引用基类的“this.id”。
【问题讨论】: