17. Marching Penguins Penguins as subclass with function.call and prototype.constructor


#1



15. Marching Penguins

So i wasn't necessarily Stuck so much, as that i thought declaring Penguin(-method) independent from Animal would be just repetition, thats what i got from the hint. Retrospective i used to much code from later Chapters, so keep in mind this is not how you're supposed to solve this. I decided to post it anyway if someone wants an example code for this or had the same idea… Now for those interested my solution:

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


// first it calls Animal function which for one
// variable is not necessary but result should be
// same. numLegs is overwritten.
function Penguin(name,numLegs){
    Animal.call(this, name);
    this.numLegs=2;
};

// create a sayName method for Penguins here
// Penguin.prototype becomes Animal.prototype
Penguin.prototype = Object.create(Animal.prototype);
// Penguin Object inherits property from its prototype function(Animal)
// thus sayName function. And construct its own.
Penguin.prototype.constructor = Penguin;


// our test code
var theCaptain = new Penguin("Captain Cook", 2);
theCaptain.sayName();


not entirely sure if everything does what i think its supposed to, there might be some redundancy witch function.call. But maybe i help someone out with this.

some references:
mozilla dev Object.prototype.constructor
mozilla dev function.(prototype.)call() to chain constructors for an object
Object Oriented Super Class Method Calling


#2

Hi Idnumber :wink:

Short comment: Unless I am missing something, you are trying to inherit by three different ways:

  1. Penguin.prototype.constructor = Penguin;
  2. Penguin.prototype = Object.create(Animal.prototype);
  3. Animal.call(this, name);

when even one:

Penguin.prototype = new Animal();

is sufficient.