【问题标题】:Javascript prototypical inheritance creates extra properties in the derived classesJavascript 原型继承在派生类中创建额外的属性
【发布时间】: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”。

【问题讨论】:

    标签: javascript inheritance


    【解决方案1】:

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

    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;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      相关资源
      最近更新 更多