This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by Sundar Nadimpalli
almost 11 years

I get an error: TypeError: Penguin is not a constructor

Here is my code:

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

var penguin = new Penguin('Pandu', 2);
penguin.sayName();

Not sure what I am doing wrong. Can anyone help?

Answer 51c05c537c82ca27ab00c4cf

3 votes

Permalink

Your use of “function Penguin() {} “ instead of “var Penguin = new object()” works because Penguin shouldn’t be an object.

A function can be a constructor, but an Object is more like directly programming the data. Think of how you used a constructor to make a penguin object. You put something like:

penguin = new Penguin(“Ralph”)

That creates the object “penguin” with properties of

  • penguin.name = “Ralph”
  • penguin.numLegs = 2
  • penguin.sayname = a function that makes it print “My name is Ralph”

The reason that even a blank penguin function (like your example) still works is because of that prototype line, it’s basically saying: Penguin is just like the animal class, and everything that makes up the animal class is used to make up the Penguin class, unless overriden directly.

Basically, you created Penguin as a blank function, and also told it to inherit all the properties from Animal, so it’s not really blank anymore.

points
Submitted by Michael Scott
almost 11 years

1 comments

Sundar Nadimpalli almost 11 years

Thank you for the explanation. Clears up my doubts regarding this. So this is the right way to do it.

Answer 51c0692152f863ad4d00d5a0

2 votes

Permalink

To answer the initial question.. the error was that they made Penguin an Object, instead of a function/class/constructor.

points
Submitted by Michael Scott
almost 11 years

Answer 51c034ae282ae36879009f50

1 vote

Permalink

Ok I was able to solve the problem by looking at exercise 6. If I define the new Penguin like this: function Penguin() { }

Instead of like this: var Penguin = new Object();

Codeacademy lets me clear the exercise. Very strange.

points
Submitted by Sundar Nadimpalli
almost 11 years

4 comments

Michael Scott almost 11 years

See my post for the reason this works. (you’re not supposed to start your own answer to your original post, unless you’ve answered the issue)

Sundar Nadimpalli almost 11 years

Sorry I didn’t know that. Should I have updated my original post instead?

Michael Scott almost 11 years

yeah.. otherwise someone answers your question in here, and it get’s confusing to someone else trying to figure it out.

Sundar Nadimpalli almost 11 years

Got it. Thanks.