inheritance - Javascript: Correct way to inherit properties/methods -


i being converted c#er javascripter. have fundamental query of how should designing "classes" far common properties/methods concerned.

below, want have "id" common property along start , stop methods. surely. "id" different across instances of myderivedclass. there myotherderivedclass needs inherit mybaseclass, wanted "id" common property in base. may thinking need right, please let me know how redesign way done typically in javascript.

var mybaseclass = function(id){ mybaseclass.prototype.id = id;     mybaseclass.prototype.start = function(){     console.log('starting item %s', this.id);     //...//     console.log('started item %s', this.id); };  mybaseclass.prototype.stop = function(){     console.log('stopping item %s', this.id);     //...//     console.log('stopped item %s', this.id); }; };  var myderivedclass = function(id){         myderivedclass.prototype.connected = false;     myderivedclass.prototype.id = id; //????? };  inherit(myderivedclass, jsdialtone.common.items.dynamicitem);  // inherit method var inherit = function(child, base){ var dummy = function(){}; dummy.prototype = base.prototype; child.prototype = new dummy(); child.prototype.constructor = child; };  var d1 = new myderivedclass('d1'); expect(d1.id).tobe('d1'); // passes var d2 = new myderivedclass('d2'); expect(d1.id).tobe('d1'); // fails, since modified prototype. 

use d2.id = 'd2' (but this.id = id in constructor); , same connected flag.

the id value not shared between instances , therefor not fitting use shared property on [[prototype]].

in general, [[prototype]] objects should not modified in respective constructor-functions because not make sense: akin setting static (or "shared") variable in c# or java constructor.


Comments