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.

  1. in male.prototype = object.create(human.prototype) prototype chain male.prototype --> human.prototype --> object.prototype --> null?
  2. in male constructor use human.call(this, eyes); call super class, have pass eyes again in male constructor pass human constructor. seems pain, there easier way this?
  3. how come see code male.prototype = new human(); ... seems incorrect. happening when that??

to answer questions:

  1. that's correct. when set male.prototype = object.create(human.prototype) set prototype chain male.prototype --> human.prototype --> object.prototype --> null. when create var sethen = new male instance (sethen) inherits prototype chain.
  2. no, need manually pass parameters base constructor function. if want set this.eyes = eyes ? "not blind" : "blind" within male function code duplication. you're doing correct.
  3. that old way of doing things (before object.create standardized). recommend don't use it. cases it's same new method. using method unwanted properties eyes on male.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

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -