Skip to content Skip to sidebar Skip to footer

Javascript Inheritance Rules

Learning JS in codecademy, confused about some technicalities regarding inheritance on lesson 18/30. Penguin is a subclass of Animal. I set Penguin's prototype to Animal, and in th

Solution 1:

food is a property that is initialized in the Animal() constructor when it is called with three parameters passed to it. Since you are never calling the constructor that way with those arguments and you are never setting the food property in your Penguin constructor, that property will be undefined (never set).

The numLegs property will have a value of 2 because your Penguin constructor always sets it to 2.

The name property will be set because you are setting it in your Penguin constructor. There is only one object here. It's not like there's a Penguin part of the object and an Animal part of the object. There's just one object and one set of properties. No matter where the property is set (which constructor or which method), once it is set, it's set on the object.

The usual method of inheritance is to create a constructor for Penguin that includes ALL the properties needed to initialize the object (or the subclass manually sets some of the arguments itself) and then in the Penguin constructor, you call the constructor of the base object and pass it the arguments that it expects.

Here would be one way to do that where the Penguin constructor calls the Animal constructor and passes the arguments for numLegs and food since they are already known for a Penguin and thus don't need to be passed in with the Penguin constructor.

functionAnimal(name, numLegs, food) {
    this.name = name;
    this.numLegs = numLegs;
    this.food = food;
}

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

// define a Penguin classfunctionPenguin(name) {
    // call parent constructor with this object and all three args it wants// so all the object properties get initialized appropriatelyAnimal.call(this, name, 2, "fish");
}

// set its prototype to be a new instance of AnimalPenguin.prototype = newAnimal();

FYI, the more modern way to set the prototype is:

Penguin.prototype = Object.create(Animal.prototype);

This avoids any side effects of the constructor and just copies the desired prototype. Object.create() requires IE9 or a simple polyfill.

Post a Comment for "Javascript Inheritance Rules"