JavaScript and prototype inheritance -
it seems though understanding javascript inheritance , how should done properly. here code:
function human(eyes) { this.eyes = eyes ? "not blind" : "blind"; } human.prototype.cansee = function () { return this.eyes; }; function male(name, eyes) { human.call(this, eyes); this.name = name; } male.prototype = object.create(human.prototype); var sethen = new male("sethen", true); console.log(sethen.cansee()); //logs "not blind" from understand, using object.create create prototype object inheritance better using new keyword. raises couple questions in head.
- in
male.prototype = object.create(human.prototype)prototype chainmale.prototype --> human.prototype --> object.prototype --> null? - in
maleconstructor usehuman.call(this, eyes);call super class, have pass eyes again inmaleconstructor passhumanconstructor. seems pain, there easier way this? - how come see code
male.prototype = new human();... seems incorrect. happening when that??
to answer questions:
- that's correct. when set
male.prototype = object.create(human.prototype)set prototype chainmale.prototype --> human.prototype --> object.prototype --> null. when createvar sethen = new maleinstance (sethen) inherits prototype chain. - no, need manually pass parameters base constructor function. if want set
this.eyes = eyes ? "not blind" : "blind"withinmalefunction code duplication. you're doing correct. - that old way of doing things (before
object.createstandardized). recommend don't use it. cases it's same new method. using method unwanted propertieseyesonmale.prototype.
when male.prototype = new human create new instance of human , assign male.prototype. hence prototype chain male.prototype --> human.prototype --> object.prototype --> null. property male.prototype.eyes don't require. should belong instance of male.
i recommend read blog post. it's primer on prototypal inheritance: aadit m shah | why prototypal inheritance matters
Comments
Post a Comment