Alternative to 17.Marching Penguins prototype


#1


I understand the lesson (17. Marching Penguins) is teaching us how to add via prototypes. As such, the below code does work correctly:

function Animal(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
};
// create a Penguin constructor here
function Penguin(name, numLegs){
    this.name = name;
    this.numLegs = numLegs
};
// create a sayName method for Penguins here
Penguin.prototype.sayName = function(){
    console.log("Hi my name is " + this.name);
};
// our test code
var theCaptain = new Penguin("Captain Cook", 2);
theCaptain.sayName();

However, could I have skipped the Penguin.protoype extension and instead added the method to the original Penguin class as follows:

function Penguin(name, numLegs){
    this.name = name;
    this.numLegs = numLegs;
    this.sayName = function(){
        console.log("Hi my name is " + this.name);
    }
};

#2

yes, you can do that, but then you don't learn how to use prototype

but agree, it is good to realize you can just add the method to the class. This should also make you realize what prototype does (adding a method to a class after creating the class)


#3

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