Javascript prototypical inheritance creates extra properties in the derived classes -
Javascript prototypical inheritance creates extra properties in the derived classes -
when inheritance in js, find properties in derived classes duplicates of base of operations class properties; can't guess how forcefulness derived class utilize properties of base of operations class. need little shove in right direction can prepare inheritance model or can alter way using prototypical inheritance.
let's start 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; } homecoming this; }; you've seen before. create next inheritance:
function base() { this.id = 0; }; base.prototype.init = function ( _id ){ this.id = _id; }; function entity(){ }; entity.inheritsfrom( base of operations ); entity.prototype.init = function( _id ){ this.parent.init.call( this, _id ); }; now utilize entity class follows:
var e = new entity(); e.init( "mickey" ); console.log( e.id ); when inspect properties of new entity class ... have 2 ids (see output below). trivial case, have spent lot of time trying work.
e: entity id: "mickey" __proto__: base of operations constructor: function entity(){ id: 0 init: function ( _id ){ parent: base of operations __proto__: base of operations why have 2 ids? derived class doesn't reference 'this.id' of base of operations class.
in inheritsfrom when new parentclassorobject base of operations constructor invoked , id property setted prototype. need alter 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; } homecoming this; }; javascript inheritance
Comments
Post a Comment