0

I'm going through a JavaScript tutorial and it's asking me to create do the following:

Create a Penguin object with the variable name penguin and any name you'd like.

Then call penguin.sayName();.

My code is as follows:

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

// Here's where I need to create the Penguin object
var penguin = {
    name: "Pinguino"
};

penguin.sayName(name);

I'm fairly certain that my code is correct up to where I set the Penguin prototype to the new instance of Animal. However when I submit the code, I get an error saying "Make sure to create a new Penguin instance called penguin!"

fluidsonic
  • 4,655
  • 2
  • 24
  • 34
D. Dub
  • 11
  • 3

2 Answers2

1

With this code:

var penguin = {
    name: "Pinguino"
};

You just create an object of class Object. To create a penguin of type Penguin, instanciate Penguin class:

var penguin = new Penguin("Pinguino");
penguin.sayName();
dooxe
  • 1,481
  • 12
  • 17
  • Aah. Thank you. I knew I was close, but I just couldn't quite get it. I'm still having trouble remembering all the vocab. If I could upvote you, I would, but alas, I do not have enough reputation, obviously. – D. Dub Oct 07 '14 at 22:07
  • No problem. I'm glad that you understand object instanciation now. – dooxe Oct 07 '14 at 22:10
0

Here are a couple of improvements to the code:

function Penguin(name) {
// do not copy paste re use your code
// but actually re use it by calling 
// the parent constructor
  Animal.call(this,name,2);
//    this.name = name;
//    this.numLegs = 2;
};

// set its prototype to be a new instance of Animal
// Do not create an instance of Parent to set the 
// prototype part of inheritance
//Penguin.prototype = new Animal();
Penguin.prototype = Object.create(Animal.prototype);
//when overwriting prototype you will have prototype.constructor
// point to the wrong function, repair that
Penguin.prototype.constructor=Penguin;

More info on constructor functions and prototype here.

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160
  • Thanks for that. I'm still very basic with JS so hopefully as I continue I'll learn more ways to write the same code in more efficient ways. – D. Dub Oct 08 '14 at 14:40