Javascript prototypical inheritance creates extra properties in the derived classes
When I do inheritance in JS, I find extra properties in the derived classes that are duplicates of the base class properties; I can't guess how to force the derived class to use the properties of the base class. I need a little shove in the right direction so that I can fix my inheritance model or that I can change the way I am using prototypical inheritance.
Let's say that I start with this typical inherit function:
Function.prototype.inheritsFrom = function( parentClassOrObject ){
if ( parentClassOrObject.constructor == Function ) {
this.prototype = new parentClassOrObject; //Normal Inheritance
this.prototype.constructor = this;
this.proto开发者_如何学编程type.parent = parentClassOrObject.prototype;
} else {
this.prototype = parentClassOrObject; //Pure Virtual Inheritance
this.prototype.constructor = this;
this.prototype.parent = parentClassOrObject;
}
return this;
};
You've probably seen this before. Now I create the following inheritance:
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 );
};
Now we use the entity class like follows:
var e = new entity();
e.init( "Mickey" );
console.log( e.id );
When I inspect the properties of my new entity class ... I now have two IDs (see output below). Obviously this is a trivial case, but I have spent a lot of time trying to get this to work.
e: entity
id: "Mickey"
__proto__: base
constructor: function entity(){
id: 0
init: function ( _id ){
parent: base
__proto__: base
Why do I have two IDs? The derived class doesn't even reference the 'this.id' of the base class.
In inheritsFrom
when you do new parentClassOrObject
the base constructor invoked and id
property setted to prototype. You need to change your method:
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;
};
精彩评论