Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript原型继承在派生类中创建额外的属性_Javascript_Inheritance - Fatal编程技术网

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

Javascript原型继承在派生类中创建额外的属性,javascript,inheritance,Javascript,Inheritance,当我在JS中进行继承时,我在派生类中发现了与基类属性重复的额外属性;我猜不出如何强制派生类使用基类的属性。我需要朝着正确的方向前进一点,这样我就可以修复我的继承模型,或者改变我使用原型继承的方式 假设我从这个典型的继承函数开始: Function.prototype.inheritsFrom = function( parentClassOrObject ){ if ( parentClassOrObject.constructor == Function ) { this.proto

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

为什么我有两个身份证?派生类甚至不引用基类的“this.id”。

inheritsFrom
中,当您执行
newparentclassorobject
时,调用基类构造函数并将
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;
};