It seems as though I am finally understanding JavaScript inheritance and how it should be done properly. Here is my 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 what I understand, using Object.create
to create your prototype object for inheritance is much better than using the new
keyword. This raises a couple questions in my head.
- In the
Male.prototype = Object.create(Human.prototype)
would the prototype chain beMale.prototype --> Human.prototype --> Object.prototype --> null
? - In the
Male
constructor where I useHuman.call(this, eyes);
to call a super class, I have to pass eyes again in theMale
constructor to pass it to theHuman
constructor. This seems like a pain, is there an easier way to do this? - How come sometimes I see code like
Male.prototype = new Human();
... This seems to be incorrect. What is actually happening when we do that??