15. why define this.name every time?



Why do we have to define this.name in every class of Animal, penguin, and Emperor, even though Emperor and penguin are going to inherit from Animal?


function Animal(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
function Penguin(name) {
    this.name = name;
    this.numLegs = 2;
Penguin.prototype = new Animal()

Notice that we didn't pass any arguments in the last line where Penguin is set to inherit from Animal? For that reason, none are set (this.name is undefined). We need to pass in a name so that property has a value.

The numLegs property overrides that of Animal.


So is there any way to create a penguin class that will inherit the name constructor from Animal?


I don't know that there is a need for such inheritance. The name is defined in the instance, not the prototype.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.