Javascript原型继承在派生类中创建额外的属性

Javascript prototypical inheritance creates extra properties in the derived classes

本文关键字:创建 属性 原型 继承 派生 Javascript      更新时间:2023-09-26

当我在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"。

inheritsFrom中,当您执行new parentClassOrObject时,调用基础构造函数并将id属性设置为prototype。你需要改变你的方法:

Function.prototype.inheritsFrom = function( parentClassOrObject ){
  if ( parentClassOrObject.constructor == Function ) {
    function tmp() {}
    tmp.prototype = parentClassOrObject;
    this.prototype = new tmp;  //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;
};