When dealing with inheritance in JavaScript, I often encounter a issue where derived classes contain duplicate properties of the base class. And yet, I struggle to understand how to ensure that the derived class leverages the properties of the base class properly. I need some guidance on either refining my approach to inheritance or modifying how I implement prototypical inheritance.
Consider starting 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.prototype.parent = parentClassOrObject.prototype;
} else {
this.prototype = parentClassOrObject; //Pure Virtual Inheritance
this.prototype.constructor = this;
this.prototype.parent = parentClassOrObject;
}
return this;
};
This is likely familiar to you. Now, let's create an inheritance scenario as follows:
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 proceed to use the entity class like so:
var e = new entity();
e.init( "Mickey" );
console.log( e.id );
Upon inspecting the properties of the new entity class ... it appears that there are two IDs present (as shown in the output below). Even though this is a simplistic example, I have struggled significantly in resolving this issue.
e: entity
id: "Mickey"
__proto__: base
constructor: function entity(){
id: 0
init: function ( _id ){
parent: base
__proto__: base
Why am I encountering this duplicated ID situation? The derived class does not even make reference to the 'this.id' property of the base class.