DRY Penguins


#1


https://www.codecademy.com/en/courses/objects-ii/3/3?curriculum_id=506324b3a7dffd00020bf661


Nothing wrong, just curious. If penguin uses the animal prototype, why do we need to give it the name property? Doesn't it automatically have the same name property as animal?


// 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();


#2

lets say we want to add more animals (cats, dogs, giraffes, you name it), then all this animals would have the same name, do you really want that?


#3

The code below results in an error from the console, but a success message from the website. I can't seem to get it to work properly...

// create your Animal class here
function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}

// create the sayName method for Animal
Animal.prototype.sayName = function() {
console.log("Hi my name is" + Animal.name());
};

// provided code to test above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();


#4

changing Animal.name() to 'this.name' results in a success message and a blank console. slight improvement?


#5

this change should be sufficient to make it work, maybe your browser is sending cached data? Refresh the page, see what happens


#6

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