15/19 inheritance


#1

When the Penguin class inherits the methods from the Animal class, why doesn't it inherit "this.numLegs = numLegs" and throw an error since numLegs is not defined?`

// the original Animal class and sayName method
function Animal(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
};

// define a Penguin class
function Penguin(name) {
    this.name = name;
    this.numLegs = 2;
};

// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();

var penguin = new Penguin("Jerry the Penguin");

penguin.sayName();`

#2

Because JS inheritance is like a layered cake. If JS interpreter is a kid looking for chocolate and it finds it on the top-most layer it does not have to look for it in the inner layers.


this.numLegs = 2;

numLegs is defined on a top level.