Javascript原型继承在派生类中创建额外的属性
Javascript prototypical inheritance creates extra properties in the derived classes
当我在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;
};
相关文章:
- 创建属性值数组,其中属性名称以特定字符串结尾
- Do let语句在全局对象上创建属性
- 如何在 javascript 中为策略设计模式创建属性
- 如何在 JavaScript 中基于另一个对象动态创建属性和对象
- 在运行时为对象创建属性
- Javascript对象:动态创建属性和属性名称
- Javascript对象属性-如果不存在,则创建属性
- 如何在使用纯js创建属性时执行某些操作
- 自动创建属性不起作用
- TypeError:无法创建属性'mapTypeId'在字符串'无法加载映射'流星错误
- 可以在任何地方用Javascript创建属性吗?
- 什么时候在当前对象和原型上创建属性?
- 在文字对象中创建属性
- 使用JSON从对象数组创建属性数组
- 如何创建属性
- 如何使用JavaScript在SVG中创建属性
- 当ngAnnotate说“不能创建属性'$methodName'..”是什么意思?
- 无法创建属性'选择'在字符串'信息技术'angularjs
- 在ng模型中动态创建属性
- 如何在ng重复作用域内创建属性