Code order in Black (and White) penguin magic


#1


Black (and White) penguin magic


Oops, try again. Make sure to create a new Penguin instance called penguin!

TypeError: penguin.sayName is not a function

Now here's my question. Why is it that if I create a penguin object FIRST, THEN inherit the properties from the Animal class, does the code not work, but if I inherit the properties from the Animal class FIRST and THEN create a new penguin Penguin object, does the code work? Surely it shouldn't matter? The only way I could see the problem occurring is when inheriting properties from another class, all current properties (and objects) from the child class are wiped. That's the only way I can see the error message "penguin.sayName is not a function" occurring, because when we say that we'll inherit the Animal class method for the Penguin class, the object "penguin" we created just before that (see code below) is destroyed.


// 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
};
var penguin = new Penguin("bob");
// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();
// var penguin = new Penguin("bob");
penguin.sayName();


#2

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